【问题标题】:Processing lists of list in Python [duplicate]在Python中处理列表列表[重复]
【发布时间】:2020-02-06 00:05:34
【问题描述】:

一直在思考和尝试如何将列表列表转换为多个列表。

比如下面的list列表:

['RZ', ['backho'], ['forest', 'arb']]

应该根据元素的最大长度转换为n-lists,因此由于第三个元素的长度,这会导致两个列表:

['RZ', 'backho', 'forest']
['RZ', 'backho', 'arb']

列表列表中的每个元素都表示为该元素选择的可能性。

【问题讨论】:

  • 你的意思是结果应该是笛卡尔积吗?
  • @schwobaseggl 请重新打开,这个问题可不是扁平化那么简单。
  • import itertools; [list(sublist) for sublist in itertools.product(*input)] 会做你想做的事吗?
  • @Bjartr 不,它没有,因为RZ 不在list 内。否则,它会。
  • @JuanPerez 您能否再解释一下输入列表的格式是什么?看起来'RZ'['backho'] 受到同等对待。例如应该发生什么[0, [1], [2, 3], [4, 5, 6]]?

标签: python list


【解决方案1】:

你可以使用itertools.product:

from itertools import product

lst = ['RZ', ['backho'], ['forest', 'arb']]
res = [list(p) for p in product([lst[0]], *lst[1:])]

print(res) # [['RZ', 'backho', 'forest'], ['RZ', 'backho', 'arb']]

【讨论】:

  • 或:res = [list(p) for p in product(*[x if isinstance(x, list) else list(x) for x in lst])] 这样简单的str 可以在任何地方。
【解决方案2】:
import itertools
for el in itertools.product(*['RZ', ['backho'], ['forest', 'arb']]):
    print(list(el))

并给出:

['R', 'backho', 'forest']
['R', 'backho', 'arb']
['Z', 'backho', 'forest']
['Z', 'backho', 'arb']

或者如果你想要一个列表列表:

[list(el) for el in itertools.product(*['RZ', ['backho'], ['forest', 'arb']])]

【讨论】:

    猜你喜欢
    • 2021-04-03
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 2011-06-15
    • 2023-02-13
    相关资源
    最近更新 更多