gpt4 book ai didi

python - 列表列表和整数列表

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

我有一个包含整数的 python 列表列表,我需要将它转换成一个列表。

如果列表不包含任何整数(仅其他列表),我可以使用此处提供的解决方案:Making a flat list out of list of lists in Python

即,

[item for sublist in main_list for item in sublist]

例如,

test_list = [[1,2,3,4,5,6], [7,8,9,10], [11,12,13,14]]
test_list = [item for sublist in test_list for item in sublist]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

但是,如果列表中包含整数,则此解决方案不起作用:

test_list_2 = [[1,2,3,4,5,6], 0, [7,8,9,10], [11,12,13,14]]
test_list_2 = [item for sublist in test_list_2 for item in sublist]

Traceback (most recent call last):

File "<ipython-input-28-c6531e09f706>", line 1, in <module>
test_list_2 = [item for sublist in test_list_2 for item in sublist]

TypeError: 'int' object is not iterable

有没有办法避免这个问题?谢谢。

最佳答案

你需要做这样的事情:

>>> test_list_2 = [[1,2,3,4,5,6], 0, [7,8,9,10], [11,12,13,14]]
>>> def lift_int(v):
... if not isinstance(v, list):
... return [v]
... else:
... return v
...
>>> test_list_2 = [item for sublist in test_list_2 for item in lift_int(sublist)]
>>> test_list_2
[1, 2, 3, 4, 5, 6, 0, 7, 8, 9, 10, 11, 12, 13, 14]

关于python - 列表列表和整数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32181160/

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