Python中的列表列表处理

2024-09-28 23:28:13 发布

您现在位置:Python中文网/ 问答频道 /正文

一直在思考和尝试如何将一个列表转换为多个列表,但没有结果。你知道吗

例如,以下列表:

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

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

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

列表列表中的每个元素都表示要为该元素选择的可能性。你知道吗


Tags: 元素列表可能性listsarbforestrzbackho
2条回答

您可以使用^{}

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']]
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']])]

相关问题 更多 >