简体   繁体   English

如何对列表中的每个其他数字进行数学运算?

[英]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.

相关问题 如何在 django 中执行数学运算? - how do i perform a math operation in django? 我如何从列表中表示一个字典,假设它旁边的其他所有数字都是它的值? - How do I represent a dictionary from a list assuming that every other number by its side is its value? 如何在python中将列表中的每个数字相互求和? - How can i sum every number in list with each other in python? 如何在python列表中的所有其他项目中添加文本? - How do I add text to every other item in a python list? Python:如何反转列表中的所有其他字符串? - Python: How do I reverse every other string in a list? 如何在日期上执行数学运算并将其在Python中排序? - How do I perform math operations on dates and sort them in Python? 如何列出 Python 中每隔十个数字的列表 - How do I make a list of every other ten numbers in Python 在引用其他行上存在的数据时,如何对DF中的每一行执行计算? - How do I perform a calculation for every row in a DF while referencing data present on some other row? 如何验证每个列表是否都包含公用号码? - How do I verify if every list contains a common number? 如何检查列表中每个项目的模除法结果,并检查每个数字是否满足条件 - How do I check the results of a modulo division for every item in a list and check if every number satisfies a condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM