我有一个清单:
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
如何修复?你知道吗
感谢您提前阅读和帮助!!你知道吗
可以使用通用解包运算符将子列表之前的项打包到另一个列表中,以便使用
+
运算符合并它们:这将返回:
简单的列表理解:
考虑到最后一个嵌套项始终是iterable(与内部项的总数无关)
输出:
相关问题 更多 >
编程相关推荐