有没有更好的方法来合并具有子列表的元组的项,而不创建下面这样的新函数?

2024-10-02 04:32:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个清单:

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

如何修复?你知道吗

感谢您提前阅读和帮助!!你知道吗


Tags: in列表newforoutput整数解决方案list
3条回答

可以使用通用解包运算符将子列表之前的项打包到另一个列表中,以便使用+运算符合并它们:

[a + b for *a, b in k_list]

这将返回:

[[1, 2, 3, 'a', 'b', 'c'], [4, 5, 6, 'd', 'e', 'f'], [7, 8, 9, 'g', 'h', 'i']]

简单的列表理解:

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

考虑到最后一个嵌套项始终是iterable(与内部项的总数无关)

k_list = [(1,2,3,['a','b','c']), (4,5,6,['d','e','f']), (7,8,9,['g','h','i'])]
res = [list(i[:-1]) + i[-1] for i in k_list]
print(res)

输出:

[[1, 2, 3, 'a', 'b', 'c'], [4, 5, 6, 'd', 'e', 'f'], [7, 8, 9, 'g', 'h', 'i']]

相关问题 更多 >

    热门问题