我有一个清单
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
是否有任何优雅的方式使它们成对工作? 我的预期是
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
答案 0 :(得分:9)
pairs = zip(*[iter(a)]*2)
是一种常见的习语
答案 1 :(得分:6)
[(a[2*i], a[2*i+1] ) for i in range(len(a)/2)]
这当然假设len(a)是偶数
答案 2 :(得分:3)
def group(lst, n):
"""group([0,3,4,10,2,3], 2) => [(0,3), (4,10), (2,3)]
Group a list into consecutive n-tuples. Incomplete tuples are
discarded e.g.
>>> group(range(10), 3)
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
"""
return zip(*[lst[i::n] for i in range(n)])
来自activestate,n元组的配方,而不仅仅是2元组
答案 3 :(得分:1)
b = []
for i in range(0,len(a),2):
b.append((a[i],a[i+1]))
a = b
答案 4 :(得分:0)
尝试使用切片和拉链。
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> zip(a[::2],a[1::2])
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]