如何在Python中概括这种列表理解?

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] * 3itertools.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)