Python中的复杂列表理解

时间:2020-03-04 18:36:51

标签: python list-comprehension operator-keyword

我在 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循环转换为嵌套列表理解吗?谢谢

1 个答案:

答案 0 :(得分:2)

仅当您实际上在构建列表时,列表理解才更快,并且只有这样(source)。就您而言,您仅在进行查找。嵌套的for循环不仅会更快,而且还会使您的代码更具可读性。

相关问题