python把列表片分成n份_如何分割每N个元素的Python列表

What I am trying to do is pretty simple, but I couldn't find how to do it.

Starting with 1st element, put every 4th element into a new list.

Repeat with the 2nd, 3rd, and 4th elements.

From:

list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b']

To:

list1 = ['1', '5', '9']

list2 = ['2', '6', 'a']

list3 = ['3', '7', 'b']

list4 = ['4', '9']

In other words, I need to know how to:

Get the Nth element from a list (in a loop)

Store it in new arrays

Repeat

解决方案

The specific solution is to use slicing with a stride:

source = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b']

list1 = source[::4]

list2 = source[1::4]

list3 = source[2::4]

list4 = source[3::4]

source[::4] takes every 4th element, starting at index 0; the other slices only alter the starting index.

The generic solution is to use a loop to do the slicing, and store the result in an outer list; a list comprehension can do that nicely:

def slice_per(source, step):

return [source[i::step] for i in range(step)]

Demo:

>>> source = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b']

>>> source[::4]

['1', '5', '9']

>>> source[1::4]

['2', '6', 'a']

>>> def slice_per(source, step):

... return [source[i::step] for i in range(step)]

...

>>> slice_per(source, 4)

[['1', '5', '9'], ['2', '6', 'a'], ['3', '7', 'b'], ['4', '8']]

>>> slice_per(source, 3)

[['1', '4', '7', 'a'], ['2', '5', '8', 'b'], ['3', '6', '9']]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值