سؤال

I'm trying to express SQL queries as python code, but I have trouble expressing the limit function

I represent an SQL table in python as

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

The following SQL expression

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

would then in python be expressed as

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

If I wanted to limit the output to 10 rows I could then write

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   

My way of expressing the limit function in python is cumbersome and not very elegant, so I was hoping that someone could help expressing this in a more elegant way.

هل كانت مفيدة؟

المحلول

You'd use iteration, list comprehensions or generators and the 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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top