[英]Iterative slicing
I am a beginner in programming, I try to learn Python, and I cannot set a correct iterative slincing of my data.我是编程初学者,我尝试学习 Python,但无法设置正确的数据迭代切片。 I have this:
我有这个:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
And I would like to obtain this, ie I do chunks of 3 items and remove half of them:我想获得这个,即我做 3 个项目的块并删除其中的一半:
a = [0, 1, 2,
6, 7, 8,
12, 13, 14,
18, 19, 20]
I tried a for loop with a % condition, but I cannot set the rule to get what I want...I did not do maths during years so it's probably a very stupid logical error...我尝试了一个带有 % 条件的 for 循环,但我无法设置规则来获得我想要的东西......多年来我没有做数学,所以这可能是一个非常愚蠢的逻辑错误......
a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18, 19, 20, 21, 22, 23]
for i in range (len(a)):
if i==0 :
a=a
elif (i-3)%6 == 0 :
a[i:i+4]=[]
else :
a=a
print(a)
Thanks a lot in advance for your help !非常感谢您的帮助!
You could use list comprehension:您可以使用列表理解:
result = [val for i in range(0, len(a), 6) for val in a[i:i+3]]
you want this?你要这个?
a= [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18, 19, 20, 21, 22, 23]
b = []
for i in range(0,len(a),6):
for j in range(i,i+3):
b.append(a[j])
print(b)
I would suggest:我会建议:
I would suggest defining edgecases.我建议定义边缘情况。 For example, what happens when the length of the array is not a multiple of 3?
例如,当数组的长度不是 3 的倍数时会发生什么?
This should be a good starting point!这应该是一个很好的起点!
Goodluck!祝你好运!
With a list comprehension and integer operations:使用列表理解和 integer 操作:
[v for v in a if (v // 3) % 2 == 0]
This of course assumes that you're working on a sorted list with values from 0-n, as in the example.这当然假设您正在处理一个值从 0 到 n 的排序列表,如示例中所示。 If you still want to use this method, you can use enumerate, too:
如果您仍想使用此方法,也可以使用 enumerate:
[v for i, v in enumerate(a) if (i // 3) % 2 == 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.