将未知数量的引用列表解压缩为for循环

时间:2017-08-07 05:54:57

标签: python-3.x

这是我想要做的。

from itertools import product

li = []
# Append arbitrary/unknown number of integers to li

ranges = [range(1, n) for n in li]

# Question 1: How to create a list of *references* whose length is that of li (or ranges)
# Is this the right way?

target_list = [None, ] * len(ranges)

# Question 2: Unpack this target_list of references in a for-loop, How to?
# Something like so (of course this does not work, just trying to convey intent)

for *target_list in product(ranges):
    # Access specific elements of target_list

如果我所做的事情的目的不明确,或者我能以任何方式更好地说出来,请告诉我。

感谢您的聆听。

1 个答案:

答案 0 :(得分:0)

事实证明,我并不需要创建一个target_list和" unpack"它在for循环中。

要实现我想做的事情,我所要做的就是将参数解压缩到product,如下所示:

from itertools import product

li = []
# Append arbitrary/unknown number of integers to li

ranges = [range(1, n) for n in li]

for target_list in product(*ranges): # Note ranges is unpacked
    # Access specific elements of target_list