2011-05-01 55 views
25

我發現下面的代碼,並與python2如何在Python 3中分塊列表?

from itertools import izip_longest 
def grouper(n, iterable, padvalue=None): 
    "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" 
    return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue) 

然而,這兼容不使用Python 3工作。我收到以下錯誤

ImportError: cannot import name izip_longest 

有人可以幫忙嗎?

我想我的[1,2,3,4,5,6,7,8,9]列表轉換爲[[1,2,3],[4,5,6],[7,8,9]]

編輯

現在低於Python3兼容

代碼從選擇的答案適應。只需將名稱從izip_longest更改爲zip_longest即可。

from itertools import zip_longest 
def grouper(n, iterable, padvalue=None): 
    "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" 
    return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue) 
+0

閱讀文檔! 「itertools」模塊文檔的Python 3版本更新了'grouper'的配方:http://docs.python.org/py3k/library/itertools.html#itertools-recipes – 2011-05-02 01:36:06

回答

42

在Python 3的itertools有一個名爲zip_longest功能。它應該和Python 2中的izip_longest一樣。

爲什麼更改名稱?您可能還注意到itertools.izip現在已經在Python 3中消失了 - 這是因爲在Python 3中,zip內置函數現在返回一個迭代器,而在Python 2中,它返回一個列表。由於不需要izip函數,因此爲了一致性重命名_longest變體也是有意義的。

1

根據the doc

>>> s = [1,2,3,4,5,6,7,8,9] 
>>> n = 3 
>>> list(zip(*[iter(s)]*n)) 
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]