【发布时间】:2014-01-16 15:52:26
【问题描述】:
给定一种支持列表迭代的编程语言,即
for element in list do
...
如果我们有一个程序将动态数量的列表作为输入,list[1] ... list[n](其中n 可以取任何值),那么迭代这些列表中每个元素组合的最佳方法是什么?
例如list[1] = [1,2], list[2] = [1,3] 然后我们遍历[[1,1], [1,3], [2,1], [2,3]]。
我认为不太好的想法:
1) 将这些列表的大产品创建到 list_product 中(例如,在 Python 中,您可以多次使用 itertools.product()),然后迭代 list_product。问题是这需要我们存储一个(可能很大的)可迭代对象。
2) 求所有列表的长度的乘积,total_length,并使用模算术类型的思想按照以下几行做一些事情。
len_lists = [len(list[i]) for i in [1..n]]
total_length = Product(len_lists)
for i in [1 ... total_length] do
total = i-1
list_index = [1...n]
for j in [n ... 1] do
list_index[j] = IntegerPartOf(total / Product([1:j-1]))
total = RemainderOf(total / Product([1:j-1]))
od
print list_index
od
然后为所有不同的组合打印list_index。
在速度方面有没有更好的方法(不太关心可读性)?
【问题讨论】:
-
子列表可以有不同数量的元素吗?