簡體   English   中英

在python中循環壓縮列表

[英]Looping zipped list in python

我在python中使用zip()函數,並在使用for循環時發現了一個問題。 這是我的代碼:

list1 = ['monday', 'tuesday', 'wednesday', 'thursday']
list2 = [1, 2, 3, 4]

zipped_list = zip(list1, list2)

print(*zipped_list)  # unpacked zipped list

for a, b in zipped_list:   # for this to work comment the print(*zipped_list) statement
    print(a, b)

此代碼的輸出是:

('monday', 1) ('tuesday', 2) ('wednesday', 3) ('thursday', 4)

Process finished with exit code 0

現在,如果我刪除print(* zipped_list)語句,那么for循環將被正確執行:

monday 1

tuesday 2

wednesday 3

thursday 4

Process finished with exit code 0

為什么會這樣?

正如第一個注釋中所指出的,zip對象與第一個print(*zipped_list) 但是,您可以首先將zip對象轉換為列表,以便能夠再次使用zip對象的值:

zipped_list = list(zip(list1, list2))

zip對象是Iterator 鏈接中的此Q / A應解釋為什么會發生這種情況:

問:我什么時候需要額外的迭代器?

答:迭代器通常需要維護某種位置狀態信息(如返回的最后一個元素的索引等)。 如果iterable保持該狀態本身,它將變得固有地不可重入(意味着你一次只能使用一個循環)。

另請查看zip文檔。 Zip相當於:

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

看到收益率表? 這使它成為像對象一樣的生成器。 因此,一旦耗盡它就會在它上面循環。 請注意,只打印zip對象也會耗盡它。

由於zip對象是生成器,因此它們按需生成元素,而不是將整個列表擴展到內存中。 這種購買的優勢在於其典型用例的效率更高。

Shadowfax回答了關於zip生成器的事情。 如果你想知道為什么你有新線...

print(*zipped_list) # => print(elm1, elm2 ,elm3...) now newlines (only one in the end)

但是像這樣:

 for a, b in zipped_list:   
     print(a, b) # each print will do a newline in the end so you have many rows...

暫無
暫無

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

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