如何把嵌套的python list转成一个一维的python list

2025-04-30 07:55:12
推荐回答(1个)
回答1:

不知道你想怎么处理那个嵌套的list?

l = [1,2,[3,4,5],'6','a',['b','c',7]]
newList = []
for item in l:
if type(item) == list:
tmp = ''
for i in item:
tmp +=str(i)+ ' '
newList.append(tmp)
else:
newList.append(item)
print(newList)
# [1, 2, '3 4 5 ', '6', 'a', 'b c 7 ']

这里只是将嵌套的子list拼接成一个字符串。
如果你想变成[1, 2, 3, 4, 5, 6, 'a', 'b'……]这种完全形式,那就把
tmp +=str(i)+ ' '
newList.append(tmp), 
换成newList.append(i)就好……顺便删除tmp = ''……