簡體   English   中英

如何在python中使用切片將列表組合在一起?

[英]How to combine lists together into one using slicing in python?

我正在嘗試將3個不同的列表合並為1個列表。 我可以使用2個列表來完成此操作,但是當我添加第三個列表時,我開始收到一條錯誤消息:

ValueError: attempt to assign sequence of size 22 to extended slice of size 17.  

每個不同的列表都應交替顯示。 如果列表中沒有更多項目要包含在“結果”中,則應僅與其他兩個列表交替顯示。 關於如何啟用此功能的任何建議?

    print len(reddit_feed_dic)      #22
    print len(favorites_feed_dic)   #22
    print len(user_videos)          #6

    result = [None]*(len(favorites_feed_dic)+len(reddit_feed_dic)+len(user_videos))
    print len(result)
    result[::3] = reddit_feed_dic
    result[1::3] = favorites_feed_dic
    result[2::3] = user_videos

這是帶有示例數據的示例:

reddit_feed_dic = [r1,r2,r3, ...r22]
favorite_feed_dic = [f1,f1,f3, ...f22]
user_videos = [u1, u2 u3, ...u6]

我希望結果是:

result = [r1,f1,u1, 
            r2, f2, u2,
            r3, f3, u3,
            r4, f4, u4,
            r5, f5, u5,
            r6, f6, u6,
            r7,f7,
            r8,f8,
            r9,f9,...

            r22,f22]
>>> from itertools import *

如果要用None填充空白:

>>> list(chain(*izip_longest('abcdef', '12345', '#!$')))
['a', '1', '#', 'b', '2', '!', 'c', '3', '$', 'd', '4', None, 'e', '5', None, 'f', None, None]

如果你不想空的物品也沒有,並假設出發名單沒有None在他們已經:

>>> filter(lambda x: x is not None, chain(*izip_longest('abcdef', '12345', '#!$')))
['a', '1', '#', 'b', '2', '!', 'c', '3', '$', 'd', '4', 'e', '5', 'f']

如果您的清單中確實沒有( None ,那就有些麻煩了。 相同的想法,但不是過濾掉“ None我們將過濾掉一個“空”對象,該對象保證不會出現在原始列表中(因為我們剛剛創建了它!)。

def interleave(*iterables):
    null = object()
    return ifilter(lambda x: x is not null, chain(*izip_longest(*iterables, fillvalue=null)))

最好的方法是使用itertools文檔提供的roundrobin配方:

>>> from itertools import cycle, islice
>>> def roundrobin(*iterables):
        "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
        # Recipe credited to George Sakkis
        pending = len(iterables)
        nexts = cycle(iter(it).next for it in iterables)
        while pending:
            try:
                for next in nexts:
                   yield next()
            except StopIteration:
                pending -= 1
                nexts = cycle(islice(nexts, pending))


>>> reddit_feed = ['r1','r2','r3']
>>> favorite_feed = ['f1','f2','f3']
>>> user_videos = ['u1','u2','u3']
>>> list(roundrobin(reddit_feed, favorite_feed, user_videos))
['r1', 'f1', 'u1', 'r2', 'f2', 'u2', 'r3', 'f3', 'u3']
    python 3.2

    from itertools import zip_longest

    result = [j for i in zip_longest(list1,list2,list3) for j in i if j!=None] 

暫無
暫無

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

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