如何分割每N个元素的Python列表 [英] How to Split Python list every Nth element

查看:527
本文介绍了如何分割每N个元素的Python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的事情很简单,但是我找不到如何做.

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

  • 从第一个元素开始,将每个第四个元素放入一个新列表.
  • 重复第2、3和4个元素.

发件人:

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

收件人:

list1 = ['1', '5', '9']
list2 = ['2', '6', 'a']
list3 = ['3', '7', 'b']
list4 = ['4', '9']

换句话说,我需要知道如何:

In other words, I need to know how to:

  • 从列表中获取第N个元素(循环)
  • 将其存储在新数组中
  • 重复

推荐答案

具体解决方案是大步使用切片:

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]从索引0开始每隔第4个元素;其他切片只会更改起始索引.

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

generic 解决方案是使用循环进行切片,并将结果存储在外部列表中;列表理解可以很好地做到这一点:

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)]

演示:

>>> 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']]

这篇关于如何分割每N个元素的Python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆