pro*_*ngs 2 python list-comprehension
我有一个整数列表说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]
Run Code Online (Sandbox Code Playgroud)
但问题是,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]
Run Code Online (Sandbox Code Playgroud)
Fre*_*Foo 11
一些基本的数学可能有帮助.首先,要意识到这a*i1+b*i2+c*i3
是两个三元素列表的内部(点)积,可以推广到
def dot_product(a, b):
return sum(x * y for x, y in zip(a, b))
Run Code Online (Sandbox Code Playgroud)
和笛卡尔积的for i1 in _1to9 for i2 in _1to9 for i3 in _1to9
循环.这是在Python标准库中,所以你有[_1to9] * 3
itertools.product
[dot_product([a, b, c], x) for x in itertools.product(_1to9, repeat=3)]
Run Code Online (Sandbox Code Playgroud)
将其推广到任意列表l
给出
[dot_product(l, x) for x in itertools.product(_1to9, repeat=len(l))]
Run Code Online (Sandbox Code Playgroud)