Python中的复杂列表理解



我在mylist中有一个记录列表,我想遍历该列表,直到找到满足规则列表中所有3条规则的第一条记录。我尝试使用嵌套列表理解,因为我认为它会比嵌套for循环更快,然而,我的逻辑有点复杂,我不确定列表理解是否可能。这是我的代码:

import operator
import timeit

def check(rec, vl, op, vr):
operations = {'>': operator.gt,
'<': operator.lt,
'>=': operator.ge,
'<=': operator.le,
'=': operator.eq,
'!=': operator.ne}
return operations[op](vl, vr)

mylist = [{'criteria': {'shipping_point': '3000', 'from_tot_weight': '250', 'to_tot_weight': '999999'}, 'result': {'ship_type': '02'}}, {'criteria': {'shipping_point': '3200', 'from_tot_weight': '350', 'to_tot_weight': '999999'}, 'result': {'ship_type': '02'}}]
rules = [{'varL': ['rec', 'criteria', 'shipping_point'], 'operator': '=', 'varR': "3000"},
{'varL': ['rec', 'criteria', 'from_tot_weight'], 'operator': '<=', 'varR': "250"},
{'varL': ['rec', 'criteria', 'to_tot_weight'], 'operator': '>=', 'varR': "250"}]

def run_1():
newlist = [rec for rec in mylist if all(check(rec, locals()[rule['varL'][0]][rule['varL'][1]][rule['varL'][2]],
rule['operator'],
rule['varR'])
for rule in rules)]
print(newlist)
def run_2():
found = False
result = []
for rec in mylist:
for rule in rules:
if check(rec, locals()[rule['varL'][0]][rule['varL'][1]][rule['varL'][2]],
rule['operator'],
rule['varR']):
found = True
else:
found = False
break
if found:
result = rec
break
print(result)
run_count = 1
print("==========List Comprehension with Locals()==========")
print(timeit.timeit(run_1, number=run_count))
print(" ")
print("==========Nested for loops==========================")
print(timeit.timeit(run_2, number=run_count))

在这段代码中,当我的列表理解找到满足规则列表中所有规则的记录时,它不会停止。实际上,如果您将mylist中的两条记录都更改为shipping_point=3000,则列表理解将产生不正确的结果。我认为这就是为什么它比嵌套的for循环花费更长的时间。是否有可能将这个嵌套的for循环转换为嵌套的列表理解?谢谢

当您实际构建列表时,列表理解只会更快,而且只是稍微快一点(源代码(。在您的情况下,您只是在进行查找。嵌套的for循环不仅速度更快,而且会使代码更可读。

相关内容

  • 没有找到相关文章

最新更新