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

使用Python连接列表中的连续子列表对,python,list,Python,List,如何成对组合列表中的子列表? 例如: list1 = [[1,2,3],[4,5],[6],[7,8],[9,10]] 结果将是: [[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] >>> 我相信有更好

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

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

[[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]
>>> 

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

您可以使用带有填充值的
zip\u 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]]

尝试使用列表理解(但要小心索引!)。它适用于子列表数为偶数或奇数的列表:

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]]
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
list1=[[1,2,3]、[4,5]、[6]、[7,8]、[9,10]]
n=len(列表1)
[list1[i]+(list1[i+1]如果i+1 [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10]]
或无岛:

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]]
使用一个简单的循环:

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
list1=[[1,2,3]、[4,5]、[6]、[7,8]、[9,10]]
长度=长度(列表1)
如果i+1
以下是(我希望)一个正确的解决方案:

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

在同一列表上工作,并删除n个[-1]个奇数子列表:

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]]
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

在成对列表中附加子列表是什么意思?你能解释一下你是怎么得到这个结果的吗?您是否只想用后面的一个扩展每个连续列表?是的,基本上就是这样,将每个子列表与其下一个连续子列表连接或扩展,但当然要避免重复元素。您能否添加一个输入/输出值重复的示例?list1=[[1,1,2],[3,1,4],[5,6,7],[1,1,2]]result在list1中=[[1,1,2,3,1,4],[5,6,7,1,1,2]]重复值与此有什么关系?
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