使用Python将列表中连续的子列表成对连接

3

如何将列表中的子列表成对组合? 例如:

list1 = [[1,2,3],[4,5],[6],[7,8],[9,10]]

结果将会是:
[[1,2,3,4,5],[6,7,8],[9,10]]

什么是在一对列表中添加子列表?您能解释一下如何得到结果吗?您只是想将每个连续的列表与其后面的列表扩展吗? - Anand S Kumar
是的,基本上就是这样,将每个子列表与其下一个连续的子列表连接或扩展,但当然要避免元素的重复。 - user2246905
您可以请提供一个带有重复值的输入/输出示例吗? - Anand S Kumar
list1=[[1,1,2], [3,1,4],[5,6,7],[1,1,2]] 的结果是 list1=[[1,1,2,3,1,4],[5,6,7,1,1,2]]。 - user2246905
1
这与重复值有什么关系? - Padraic Cunningham
8个回答

5

您可以使用zip_longest和填充值(以防列表包含奇数个子列表)来压缩对list1的迭代器。在zip生成器对象上运行列表推导式允许您连接连续的列表对:

>>> from itertools import zip_longest # izip_longest in Python 2.x
>>> x = iter(list1)
>>> [a+b for a, b in zip_longest(x, x, fillvalue=[])]
[[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]

3
尝试使用列表推导式(但要小心索引!)。它适用于具有偶数或奇数子列表的列表:
list1 = [[1, 2, 3], [4, 5], [6], [7, 8], [9, 10]]
n = len(list1)

[list1[i] + (list1[i+1] if i+1 < n else []) for i in xrange(0, n, 2)]
=> [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]

2
list1=[[1,2,3],[4,5],[6],[7,8],[9,10]]

length = len(list1)
new_list = [ list1[i]+list1[i+1] if i+1 < length 
                                 else [list1[i]] for i in range(0,length,2) ] 

print(new_list)

0
在同一个列表上工作,删除倒数第n个[-1]奇数子列表:
for i in range(len(l)/2):#here we go only to last even item
    l[i]+=l[i+1]#adding odd sublist to even sublist
    l.pop(i+1)#removing even sublist

0
>>> list1=[[1,2,3],[4,5],[6],[7,8],[9,10]]
>>> list1
[[1, 2, 3], [4, 5], [6], [7, 8], [9, 10]]

现在我们可以做到:

>>> test = [list1[0]+list1[1]]+[list1[2]+list1[3]]+list1[4]
>>> test
[[1, 2, 3, 4, 5], [6, 7, 8], 9, 10]
>>> 

我相信有更好的方法,但这是我能想到的方法!


0
list1 = [[1, 2, 3], [4, 5], [6], [7, 8], [9, 10]]
from itertools import islice, chain

print([list(chain.from_iterable(islice(list1, i, i + 2)))
       for i in range(0, len(list1), 2)])
[[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]

或者不使用islice:

print([list(chain.from_iterable(list1[i:i+2]))
       for i in range(0, len(list1), 2)])
 [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]

0
使用简单的循环:
list1=[[1,2,3],[4,5],[6],[7,8],[9,10]]

newlist = []

for i in range(0, len(list1), 2):
    newlist.append(list1[i] + list1[i+1])
if len(list1) % 2 > 0:
    newlist.append(list1[-1])

print newlist

0

这是(我希望)一个正确的解决方案:

def pair_up(ls):
    new_list = []
    every_other1 = ls[::2]
    every_other2 = ls[1::2]

    for i in range(len(every_other2)):
        new_list.append(every_other1[i]+every_other2[i])

    if len(ls) % 2 == 1:
        new_list.append(ls[-1])

    return new_list

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接