首页 > 解决方案 > 有没有更好的方法来合并具有子列表的元组的项目,而无需创建如下所示的新函数?

问题描述

我有一个清单:

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”对象不可迭代

如何解决这个问题?

感谢您的阅读和提前帮助!!

标签: pythonnested-lists

解决方案


只需列表理解:

>>> [(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')]

推荐阅读