2013-07-16 54 views
0

我試圖表達SQL查詢,Python代碼,但我有麻煩表達限制功能SQL映射到Python

我代表了一個Python SQL表作爲

[{'col1':val, 'col2':val,...},...] 

下面的SQL表達式

SELECT x.val, y.val 
FROM R x, S y 
WHERE x.id = y.id 

然後將在Python中表示爲

for x in R: 
    for y in S: 
     if x["id"] == y["id"]: 
     x["val"], y["val"] 

如果我想限制輸出到10行,我可以那麼寫

i = 0 
for x in R: 
    for y in S: 
     if x["id"] == y["id"]: 
     x["val"], y["val"] 
     i += 1 
     if i == 10: 
      break 
    if i == 10: 
     break 

我在Python表達限制功能的方式是麻煩,不是很優雅,所以我希望有人能幫助表達這以更優雅的方式。

回答

0

你會使用迭代,列表推導或發電機和itertools module

from itertools import product, islice 

# all values, generator expression 
query = ((x['val'], y['val']) for x, y in product(R, S) if x['id'] == y['id']) 

# just the first 10 
limited = islice(query, 10) 

for row in limited: 
    print row