gpt4 book ai didi

python - 将列表列表分解为具有不可迭代列表元素的单个列表

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:57 25 4
gpt4 key购买 nike

引用: python decompose a list Flattening a shallow list in Python

虽然上述解决方案很有帮助,但我的问题略有不同,我想知道是否有 pythonic 方法来解决它。

a = [['a-3','b-3'],'r',['j']]

我想要的是一种使“a”等于以下内容的简洁方法:

a = ['a-3','b-3','r','j']

我一直在使用 python 2.4,因此兼容 2.4 的 pythonic 解决方案会很棒,但我仍然会发现 2.7+ 示例也很有趣。

主要问题是存在不可迭代的元素,否则 sum(lst,[]) 工作得很好,2.7+ 的 chain 方法也是如此

最佳答案

Pythonic 解决方案可能意味着很多事情。用readability counts (PEP 20) 请记住,这是我对该主题的贡献:

def dec(input_, output_):
if type(input_) is list:
for subitem in input_:
dec(subitem, output_)
else:
output_.append(input_)

例子:

input_ = [['a-3','b-3', ['x','hello', ['3','b']]],'r',['j']]
output_ = ['a-3', 'b-3', 'x', 'hello', '3', 'b', 'r', 'j']

关于python - 将列表列表分解为具有不可迭代列表元素的单个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6498671/

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