python - 一般来说,遍历未知数量列表的最佳方法是什么?

标签 python list iteration

给定一种支持通过列表进行迭代的编程语言,即

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

在速度方面有没有更好的方法(不太关心可读性)?

最佳答案

1) Create a big product of these lists into list_product (e.g. in Python you could use itertools.product() multiple times) and then iterate over list_product. Problem is that this requires us to store a (potentially huge) iterable.

itertools(以及一般的迭代器)的要点是它们不会一次构建整个结果,而是一次从结果中创建和返回项。因此,如果您有一个列表列表 ListOfLists 并且您希望所有元组都包含其中每个列表中的一个元素,请使用

for elt in itertools.product(*ListOfLists):
   ...

请注意,您只需调用一次product它既简单又高效。

关于python - 一般来说,遍历未知数量列表的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21166536/

相关文章:

Python空闲。自动完成/显示完成不起作用

python - 在遍历迭代器时重新分配迭代器的值

java - 如何在一定数量的迭代后重新启动 do while 循环

iteration - 使用 x1 = (x0 - a/x0)/2 的平方根迭代

python - pip 和 virtualenv(没有 virtualenvwrapper): pip install package_name gives permission denied but using sudo installs globally

Python CSV 阅读器未按我预期的方式读取 CSV 数据

python - 在Python中一次迭代一个字符串2(或n)个字符

python - 字符串转 float 错误

c++ - 在C++中使用2个参数和一个lambda函数检查列表中元素的存在

arrays - 为什么在 Go 中很少使用列表?