我有一个整数列表 l1=[a,b,c]
和 _1to9=range(1,10)
。我想得到这个:
[a*i1+b*i2+c*i3 for i1 in _1to9 for i2 in _1to9 for i3 in _1to9]
但问题是 l1
不一定是 3 个元素的列表。那么我该如何概括呢?
编辑:帮助形象化我想要实现的目标:
>>> l1=[10001,1010, 100]
>>> [l1[0]+i1+l1[1]*i2+l1[2]*i3 for i1 in _1to9 for i2 in _1to9 for i3 in _1to9]
最佳答案
一些基础数学可能会有所帮助。首先,意识到 a*i1+b*i2+c*i3
是 inner (dot) product两个三元素列表,可以概括为
def dot_product(a, b):
return sum(x * y for x, y in zip(a, b))
和for i1 in _1to9 for i2 in _1to9 for i3 in _1to9
循环 Cartesian product [_1to9] * 3
。它在 Python 标准库中作为 itertools.product
,所以你有
[dot_product([a, b, c], x) for x in itertools.product(_1to9, repeat=3)]
将其推广到任意列表 l
给出
[dot_product(l, x) for x in itertools.product(_1to9, repeat=len(l))]
关于python - 我如何在 Python 中概括这种列表理解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10673798/