每个P编号取N个数字

时间:2018-01-22 12:32:13

标签: python list

我想在列表中的每个P对象的N个对象中列出一个列表。

为简单起见,免得说我有一个整体列表:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

如果我想每2个对象获取2个对象,我希望这样:

[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]

现在每3个对象有2个对象:

[2, 3], [5, 6], [8, 9], [11, 12]

最狡猾的方式是什么?

1 个答案:

答案 0 :(得分:1)

切片和拉链怎么样:

a = [i for i in range(13)]
print('a =',a)

offset = 1
step = 2
b = [(x,y) for x,y in zip(a[offset::step],a[offset+1::step])]
print('b =', b)

offset = 2
step = 3
c = [(x,y) for x,y in zip(a[offset::step],a[offset+1::step])]
print('c =',c)

给出

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
b = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]
c = [(2, 3), (5, 6), (8, 9), (11, 12)]

修改

要将上述内容概括为任意NP,您可以使用slices进行列表索引:

def list_segmenter(L, N, P):
    """small function to segment a list (L) into chunks of size N with step size P"""
    slices = [slice(P+i-1,len(L),P) for i in range(N)]
    lists = [L[s] for s in slices]
    return list(zip(*lists))

a = [i for i in range(13)]

##testing:
print(list_segmenter(a,2,2))
print(list_segmenter(a,2,3))
print(list_segmenter(a,4,3))

,输出为:

[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]
[(2, 3), (5, 6), (8, 9), (11, 12)]
[(2, 3, 4, 5), (5, 6, 7, 8), (8, 9, 10, 11)]