2012-12-01 62 views

回答

2

itertools recipes section

def grouper(n, iterable, fillvalue=None): 
    "Collect data into fixed-length chunks or blocks" 
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx 
    args = [iter(iterable)] * n 
    return izip_longest(fillvalue=fillvalue, *args) 

然後調用與:

for paired in grouper(2, inputlist): 
    # paired is a tuple of two elements from the inputlist at a time. 

grouper返回迭代;如果你有一個列表,只需消耗迭代到一個新的列表:

newlist = list(grouper(2, inputlist)) 
+0

+1。謝謝一堆 – Flavius

+0

如果'izip_longest'沒有定義(python2,我真的不能使用py3)? – Flavius

+0

它在Python 2中定義;蟒蛇2.6及以上,看到http://docs.python.org/2/library/itertools.html#itertools.izip_longest –

2
a = [1,2,3,4,5,6] 
b = [a[i]+a[i+1] for i in xrange(0,len(a),2)] 
+0

+1。感謝一堆 – Flavius

2
li = [1,2,10,20,100,200,2000,3000,2,2,3,3,5,5] 
print li 

it = iter(li) 
if len(li)%2==0: 
    print [x+it.next() for x in it] 

[1, 2, 10, 20, 100, 200, 2000, 3000, 2, 2, 3, 3, 5, 5] 
[3, 30, 300, 5000, 4, 6, 10] 
+0

+1。涼!有用! – Flavius

+0

@Flavius當然,Python的迭代器非常棒! – eyquem