[英]How do I perform math on every other number in a list?
Eg: How do I change 例如:如何更改
a = [1,2,3,4]
to this: 对此:
a = [2,2,6,4]
so every other element is doubled? 所以其他所有元素都会加倍吗?
If you want to do it in place, you can use slice assignment: 如果要就地执行,可以使用切片分配:
>>> a[::2] = [x*2 for x in a[::2]]
>>> a
[2, 2, 6, 4]
You can loop through every other index: 您可以遍历其他所有索引:
for index in range(0, len(your_list), 2):
your_list[index] *= 2
You can also do it using slice assignment, as @mgilson notes: 您也可以使用切片分配完成此操作,如@mgilson所述:
your_list[::2] = [x*2 for x in your_list[::2]]
While this is certainly more concise, it may also be more confusing for the average person reading through the code - assigning to a slice with a non-default skip factor isn't very intuitive. 尽管这当然更简洁,但对于普通人阅读代码也可能更加令人困惑-使用非默认跳过因子分配给切片并不十分直观。
There is another way to take two steps at a time a little more intuitive, like this 还有另一种方法,一次可以更直观地执行两个步骤,就像这样
for i in range(len(yourList)/2):
yourList[2*i] = 2*yourList[2*i]
Though I do like the neat tricks used in the other answers, perhaps a more verbose and less-language specific explanation of what's going on is as follows: 尽管我确实喜欢其他答案中使用的巧妙技巧,但可能会发生什么事,对问题进行了更为详细和较少语言的具体解释如下:
for i in range(0, len(a)): # Iterate through the list
if i%2 == 0: # If the remainder of i ÷ 2 is equal to 0...
a[i] = a[i] * 2 # Change the current element to twice what it was
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.