我有一个包含整数的列表的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
有没有办法规避这个问题?感谢。
答案 0 :(得分:4)
你需要做这样的事情:
>>> 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]
答案 1 :(得分:3)
由于您试图压缩列表,我认为最好的方法是使用generator function。请注意,这会递归地压缩您的列表而不仅仅是一个级别。
>>> def flatten(items):
... for item in items:
... if isinstance(item, list):
... yield from flatten(item)
... else:
... yield item
...
>>> list(flatten(test_list_2))
[1, 2, 3, 4, 5, 6, 0, 7, 8, 9, 10, 11, 12, 13, 14]
答案 2 :(得分:0)
如果你想继续列表(in)理解,你可以这样做:
test_list = [[1,2,3,4,5,6], 0, [7,8,9,10], [11,12,13,14]]
print [item for sublist in test_list for item in (sublist if isinstance(sublist, list) else [sublist])]
test_list = [[1,2,3,4,5,6], 0, [7,8,9,10], 1, 2, 3, [11,12,13,14], 1234]
print [item for sublist in test_list for item in (sublist if isinstance(sublist, list) else [sublist])]
让它更难理解。
答案 3 :(得分:0)
你也可以尝试这个
def convert_to_list(num):
return [num] if not isinstance(num, list) else num
然后使用itertools
>>>import itertools
itertools.chain(*map(convert_to_list, test_list_2))
<itertools.chain at 0x7ff211650550>
>>>list(itertools.chain(*map(convert_to_list, test_list_2)))
[1, 2, 3, 4, 5, 6, 0, 7, 8, 9, 10, 11, 12, 13, 14]
答案 4 :(得分:0)
def convert(data):
result = []
for sublist in test_list_2:
if type(sublist) is list:
result += sublist
else:
result.append(sublist)
return result
convert函数将列表和整数列表转换为列表
答案 5 :(得分:0)
你也可以简单地使用:
test_list = reduce(lambda x, y: x + (y if isinstance(y, list) else [y]), test_list)