如何在Python中的列表理解中保存重复计算?

时间:2017-07-08 17:19:44

标签: python python-3.x list-comprehension

在以下Python代码中:

keyboards = [3, 1]
drivers = [5, 2, 8]
upper_limit = 10
sums = [k + d for k in keyboards for d in drivers if (k + d) <= upper_limit]

我希望将k+d的结果存储在列表推导中,以便可以在列表推导中引用它。是否可以在Python3中使用?

我知道我们可以做到以下几点:

sums = []
for k in keyboards:
    for d in drivers:
        s = k + d
        if s <= upper_limit:
            sums.append(s)

但我希望避免附加的副作用。

1 个答案:

答案 0 :(得分:4)

只有for循环可以在列表理解中分配新名称,因此如果您需要本地&#39;要引用计算的变量,您需要找到添加额外循环的方法。

您可以在计算k + d的单个元素元组上添加另一个循环:

sums = [kd for k in keyboards for d in drivers for kd in (k + d,) if d <= upper_limit]

或者您也可以使用生成器表达式:

sums = [kd for kd in (k + d for k in keyboards for d in drivers) if kd <= upper_limit]

在后一种情况下,您可以先将该表达式存储为单独的变量:

kd_calc = (k + d for k in keyboards for d in drivers)
sums = [kd for kd in kd_calc if kd <= upper_limit]

演示:

>>> keyboards = [3, 1]
>>> drivers = [5, 2, 8]
>>> upper_limit = 10
>>> [kd for k in keyboards for d in drivers for kd in (k + d,) if d <= upper_limit]
[8, 5, 11, 6, 3, 9]
>>> [kd for kd in (k + d for k in keyboards for d in drivers) if kd <= upper_limit]
[8, 5, 6, 3, 9]
>>> kd_calc = (k + d for k in keyboards for d in drivers)
>>> [kd for kd in kd_calc if kd <= upper_limit]
[8, 5, 6, 3, 9]