gpt4 book ai didi

python - 使用 python 将嵌套列表转换为行

转载 作者:行者123 更新时间:2023-12-04 03:33:45 25 4
gpt4 key购买 nike

我遇到这样一种情况,我的本地递归实现程序输出的是一个嵌套列表,非常类似于树。设计的嵌套列表是对复杂结构的抽象。我需要的是尽可能多地将嵌套列表解析为许多不同的行(可选地实现递归)。

之前我试过 anytree但我的需求很复杂,虽然很好,但并没有满足我量身定制的需求。请注意嵌套列表是多维的

输入 1

list = [a,b,[c,d]]

输出 1

row1 : a,b,c
row2 : a,b,d

输入 2

list = [a,b,[c,[d,[e,f]]]]

输出 2

row1 : a,b,c
row2 : a,b,d,e
row3 : a,b,d,f

输入 3

list = [a,[b,c],[d,e]]

输出 3

row1 : a,b,d
row2 : a,b,e
row3 : a,c,d
row4 : a,c,e

1。输出中的行仅用于表示目的,输出肯定是包含许多元素的列表

2。 a,b,c,d,etc 都是对象

我对印度语进行了独立研究,因此找不到比嵌套列表更好的方法来实现关键递归输出。如果您有嵌套列表表示形式,也可以随意提出适合以更简单的方式获取输出的目的的任何替代方法。

最佳答案

您可以对 itertools.product 使用递归:

import itertools as it
def flatten(d, s = False):
if not s:
l = [[i] if not isinstance(i, list) else flatten(i, True) for i in d]
yield from it.product(*l)
else:
for i in d:
if not isinstance(i, list):
yield i
else:
yield from flatten(i, False)

def form_t(d):
for i in d:
if not isinstance(i, tuple):
yield i
else:
yield from form_t(i)

all_lists = [['a', 'b', ['c', 'd']], ['a', 'b', ['c', ['d', ['e', 'f']]]], ['a', ['b', 'c'], ['d', 'e']]]
for i in all_lists:
print([tuple(form_t(j)) for j in flatten(i)])

输出:

[('a', 'b', 'c'), ('a', 'b', 'd')]
[('a', 'b', 'c'), ('a', 'b', 'd', 'e'), ('a', 'b', 'd', 'f')]
[('a', 'b', 'd'), ('a', 'b', 'e'), ('a', 'c', 'd'), ('a', 'c', 'e')]

关于python - 使用 python 将嵌套列表转换为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67352577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com