在python中连接列表中的选定元素

时间:2012-06-06 15:03:33

标签: python list

我有一个(python) list of lists,如下所示

biglist=[ ['1','123-456','hello','there'],['2','987-456','program'],['1','123-456','list','of','lists'] ]

我需要采用以下格式

biglist_modified=[ ['1','123-456','hello there'],['2','987-456','program'],['1','123-456','list of lists'] ]

我需要在每个内部列表中连接third element onwards。我尝试使用list comprehensions来实现这一点,

def modify_biglist(bigl):
    ret =[]
    for alist in bigl:
        alist[2] = ' '.join(alist[2:])
        del alist[3:]
        ret.append(alist)
    return ret

这可以完成这项任务......但看起来有点复杂 - 有一个局部变量ret并使用del?有人可以提出更好的建议

3 个答案:

答案 0 :(得分:7)

[[x[0], x[1], " ".join(x[2:])] for x in biglist]

或就地:

for x in biglist:
    x[2:] = [" ".join(x[2:])]

答案 1 :(得分:5)

要修改列表,您可以使用以下简化代码:

for a in big_list:
    a[2:] = [" ".join(a[2:])]

答案 2 :(得分:1)

应该这样做:

[x[:2] + [" ".join(x[2:])] for x in biglist]

略短。