Outline
lis = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
从lis中每次取两个元素,且所取不重复:
[1, 2]
[3, 4]
[5, 6]
[7, 8]
[9, 10]
实现
method1
ret = [] a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(0,len(a), 2): ret.append(a[i:i+2]) print(a[i:i+2]) # [1, 2] # [3, 4] # [5, 6] # [7, 8] # [9, 10]
method2
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for r in [a[i:i + 2] for i in range(0, len(a), 2)]: # 列表生成式 print(r) # [1, 2] # [3, 4] # [5, 6] # [7, 8] # [9, 10]