簡體   English   中英

使用Python連接列表中的連續子列表對

[英]Concatenate pairs of consecutive sublists in a list using Python

如何將列表中的子列表成對組合? 例如:

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

結果將是:

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

你可以使用帶有填充值的zip_longest (如果你的列表有奇數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]]

嘗試使用列表推導(但要小心索引!)。 它適用於具有偶數或奇數子列表的列表:

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

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

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

使用簡單的循環:

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

這是(我希望)一個正確的解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM