【问题标题】:Is there a substitute of hiearchical nested FOR loop?是否有分层嵌套 FOR 循环的替代品?
【发布时间】:2019-12-02 04:47:46
【问题描述】:

如果嵌套的 FOR 循环没有互连,您可以使用 itertools.product() 替换它们。

for x, y in product(range(20), range(17)): ....

问题是有一种方法可以对分层嵌套的 FOR 循环 ..f.e 执行相同的操作。假设我有列表列表:

for level2 in LoL :
  for level3 in level2 :
    for level4 in level3 :
       .....
         t1, t2,..,tn = levelM

LoL 的结构可能是这样的,只是一个例子:

[[[1, 9], [1, 6], [1, 8], [1, 6], [1, 2]],
 [[5, 8], [5, 11], [5, 14], [5, 6], [5, 11]],
 [[7, 12], [7, 13], [7, 10], [7, 9], [7, 12]],
 [[22, 25], [22, 30], [22, 25], [22, 26], [22, 26]],
 [[55, 57], [55, 55], [55, 55], [55, 56], [55, 61]]]

输出无所谓,我想知道是否有像product()这样的快捷功能/结构

我看到的唯一其他方式是递归,但这更复杂。

product() 隐藏了结构......现在@RaySteam 说过......可能是扁平化它的功能!直到最后一级,所以它返回元组列表,因为这是你在正常情况下通常所做的......即对数据做一些事情……以循环的方式

【问题讨论】:

  • 嵌套是否随意?我的意思是它有固定的深度吗?
  • 所有的嵌套级别也是一样的吗?你想要的输出是一个平面列表,对吗?
  • 这似乎是一个多维数组,因此,您可以使用nditer
  • 你想对嵌套列表中的元素做什么?因为这真的会有所作为。

标签: python loops for-loop nested


【解决方案1】:

嵌套for循环是一种隐藏“扁平化”应用到多级数据结构的方法,因此这种模式的一个捷径是对扁平化列表的结果进行操作。

关键是 Python 当前(将来也可能)缺少用于任意嵌套列表的展平功能。更多信息请参见 threadpost

此外,您不希望结构完全变平,因为您想处理最里面的对。

这是我为这个特定用例编写的一些代码:

from itertools import chain

# Flattens i times.
# You need to know how much you need to flatten
# Assumes that nesting level doesn't vary.
def almost_flat(lol, i):
  x = lol
  for _ in range(i):
    x = chain.from_iterable(x)
  return x

# Flattens until it obtains a list-of-lists
# Also relies on fixed nesting structure.
# implemented recursively although you may unroll it in tail recursive manner.
def flat(ls):
  if not isinstance(ls[0][0], list, tuple):
    return ls
  else:
    out = []
    for x in ls:
     out.extend(x)
    return flat(out)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-03
    • 2020-12-22
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多