我有一个列表:
k_list = [(1,2,3,['a','b','c']), (4,5,6,['d','e','f']), (7,8,9,['g','h','i'])]
想像这样合并每个元组的子列表:
[(1, 2, 3, 'a', 'b', 'c'), (4, 5, 6, 'd', 'e', 'f'), (7, 8, 9, 'g', 'h', 'i')]
或
[[1, 2, 3, 'a', 'b', 'c'], [4, 5, 6, 'd', 'e', 'f'], [7, 8, 9, 'g', 'h', 'i']]
我想出了以下解决方案:
new_list =[]
def removeNesting(nest):
for e in nest:
if type(e) == list:
removeNesting(e)
else:
output.append(e)
return output
for i in k_list:
output = []
new_list.append(removeNesting(i))
print new_list
但我觉得这不是一个理想的解决方案,所以尝试在不使用函数的情况下做一些事情,当列表中没有整数时,下面的代码工作正常:
new_list1 = []
for e in k_list:
total = []
for i in e:
total += i
new_list1.append(total)
print new_list1
但是当列表中有整数时,我在这一行得到错误:total += i
TypeError: 'int' object is not iterable
如何解决这个问题?
提前感谢您的阅读和帮助!!
请您参考如下方法:
简单的列表理解:
>>> [(a,b,c,*d) for a,b,c,d in k_list]
[(1, 2, 3, 'a', 'b', 'c'), (4, 5, 6, 'd', 'e', 'f'), (7, 8, 9, 'g', 'h', 'i')]
