【问题标题】:Best way to iterate through unknown number of lists in general?一般来说,遍历未知数量列表的最佳方法是什么?
【发布时间】: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

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

【问题讨论】:

  • 子列表可以有不同数量的元素吗?

标签: python list iteration


【解决方案1】:

1) 将这些列表的大产品创建到 list_product 中(例如,在 Python 中,您可以多次使用 itertools.product()),然后遍历 list_product。问题是这需要我们存储一个(可能很大的)可迭代对象。

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

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

请注意,您只需拨打product 一次。简单高效。

【讨论】:

    【解决方案2】:

    您可以使用itertools.product 而无需具体化列表:

    >>> from itertools import product
    >>> lol = [[1,2],[1,3]]
    >>> product(*lol)
    <itertools.product object at 0xaa414b4>
    >>> for x in product(*lol):
    ...     print x
    ...     
    (1, 1)
    (1, 3)
    (2, 1)
    (2, 3)
    

    就性能而言,花更多时间思考优化它的方法很容易,这比您希望从优化中获得的收益要多。如果您在循环内做任何事情,那么迭代开销本身很可能可以忽略不计。 (最常见的例外是紧密的数字循环,在这种情况下,您应该尝试以 numpythonically 代替。)

    我的建议是使用itertools.product 并继续您的一天。

    【讨论】:

      猜你喜欢
      • 2011-04-24
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 2012-07-16
      • 2019-11-20
      • 1970-01-01
      相关资源
      最近更新 更多