如何使用python对索引中的每个第n个元素进行切片? [英] How to slice every nth element in index using python?
问题描述
这可能看起来像是一个简单的问题,但我不知道解决方案.
this might look like a simple question but I could not figure out the solution.
假设我有此列表
my_list = [1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,88,99]
我正在尝试切片此列表中的项目并按索引递增.简而言之,我想得到这样的结果
I am attempting to slice item in this list and increment it by index. In short, I want to get the result like this
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 11]
[9, 11, 22]
[11, 22, 33]
[22, 33, 44]
[33, 44, 55]
[44, 55, 66]
[55, 66, 77]
[66, 77, 88]
[77, 88, 99]
但是我得到的是这样的
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 11]
[9, 11, 22]
[11, 22, 33]
[22, 33, 44]
[33, 44, 55]
[44, 55, 66]
[55, 66, 77]
[66, 77, 88]
[77, 88, 99]
[88, 99]
[99]
我想将my_list
切成几个较小的集合,每个集合的长度为3.但是我得到的结果还包括长度小于3的列表.
I want to slice my_list
to several smaller set each with length of 3. But the result I got also included the list that have length below than 3.
这是我使用的python脚本
This is the python script I use
my_list = [1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,88,99]
m = 0
def incr():
global m
for n in range(len(my_list)):
if n < len(my_list):
n = m + 3
new_list = my_list[m:n]
print new_list
m+=1
else:
pass
incr()
我认为我可以添加if len(new_list) < 3
,但是我不太确定该如何修改脚本.
I figured that I could add if len(new_list) < 3
but I do not quite sure how should I modify the script for that.
谢谢您的帮助.
推荐答案
[my_list[i:i+3] for i in range(len(my_list)-2)]
小解释:
-
我使用了列表理解
结果列表中包含的项目数为len(my_list)-2)
The number of items the resulting list have is len(my_list)-2)
每个结果项都是根据原始列表[i:i+3]
Each result item is built slicing three consecutive items from the original list [i:i+3]
i
从0开始获取结果列表的第一项,然后将一个位置(递增一个)移至第二项,依此类推.依此类推.
i
started at 0 to get the first item of the result list and then shift one position (being incremented by one) to get the second item and so on..
这篇关于如何使用python对索引中的每个第n个元素进行切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!