基本python:如何增加列表中项目的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16903264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:57:11  来源:igfitidea点击:

Basic python: how to increase value of item in list

python

提问by Gabriel

This is such a simple issue that I don't know what I'm doing wrong. Basically I want to iterate through the items in an empty list and increase each one according to some criteria. This is an example of what I'm trying to do:

这是一个如此简单的问题,我不知道我做错了什么。基本上我想遍历空列表中的项目并根据某些标准增加每个项目。这是我正在尝试做的一个例子:

list1 = []
for i in range(5):
    list1[i] = list1[i] + 2*i

This fails with an list index out of rangeerror and I'm stuck. The expected result (what I'm aiming at) would be a list with values:

这因list index out of range错误而失败,我被卡住了。预期结果(我的目标)将是一个包含值的列表:

[0, 2, 4, 6, 8]

Just to be more clear: I'm not after producing that particularlist. The question is about how can I modify items of an empty list in a recursive way. As gnibbler showed below, initializing the list was the answer. Cheers.

更明确地说:我不是在制作那个特定的列表之后。问题是关于如何以递归方式修改空列表的项目。正如 gnibbler 所示,初始化列表就是答案。干杯。

采纳答案by John La Rooy

Ruby (for example) lets you assign items beyond the end of the list. Python doesn't - you would have to initialise list1 like this

例如,Ruby 允许您分配列表末尾以外的项目。Python 没有 - 你必须像这样初始化 list1

list1 = [0] * 5

回答by Ryan Saxe

So when doing this you are actually using i so you can just do your math to i and just set it to do that. there is no need to try and do the math to what is going to be in the list when you already have i. So just do list comprehension:

因此,在执行此操作时,您实际上是在使用 i,因此您可以对 i 进行数学运算,然后将其设置为这样做。当您已经拥有i. 所以只需做列表理解:

list1 = [2*i for i in range(5)]

Since you say that it is more complex, just don't use list comprehension, edit your for loop as such:

既然你说它更复杂,就不要使用列表理解,编辑你的 for 循环:

for i in range(5):
    x = 2*i
    list1[i] = x

This way you can keep doing things until you finally have the outcome you want, store it in a variable, and set it accordingly! You could also do list1.append(x), which I actually prefer because it will work with any list even if it's not in order like a list made with range

这样你就可以继续做事情,直到你最终得到你想要的结果,把它存储在一个变量中,并相应地设置它!你也可以这样做list1.append(x),我实际上更喜欢它,因为它可以处理任何列表,即使它不像用range

Edit: Since you want to be able to manipulate the array like you do, I would suggest using numpy! There is this great thing called vectorizeso you can actually apply a function to a 1D array:

编辑:由于您希望能够像您一样操作数组,我建议使用 numpy!有一个很棒的东西叫做vectorize,所以你实际上可以将一个函数应用于一维数组:

import numpy as np
list1 = range(5)
def my_func(x):
    y = x * 2
vfunc = np.vectorize(my_func)
vfunc(list1)
>>> array([0, 2, 4, 6, 8])

I would advise only using this for more complex functions, because you can use numpy broadcastingfor easy things like multiplying by two.

我建议只将它用于更复杂的功能,因为您可以使用numpy 广播来进行简单的事情,例如乘以 2。

回答by David Cain

You may also wish to consider using numpy. The multiplication operation is overloaded to be performed on each element of the array. Depending on the size of your list and the operations you plan to perform on it, using numpyvery well may be the most efficient approach.

您也可以考虑使用numpy. 乘法运算被重载以对数组的每个元素执行。根据您的列表的大小和您计划对其执行的操作,numpy很好地使用可能是最有效的方法。

Example:

例子:

>>> import numpy
>>> 2 * numpy.arange(5)
array([0, 2, 4, 6, 8])

回答by Chris.Stover

I would instead write

我会写

for i in range(5):
    list1.append(2*i)

回答by Marichyasana

Your list is empty, so when you try to read an element of the list (right hand side of this line)

您的列表是空的,因此当您尝试读取列表的元素时(此行的右侧)

list1[i] = list1[i] + 2*i

it doesn't exist, so you get the error message.

它不存在,因此您会收到错误消息。

回答by SgtMajorJay

Yet another way to do this is to use the append method on your list. The reason you're getting an out of range error is because you're saying:

另一种方法是使用列表中的 append 方法。您收到超出范围错误的原因是因为您在说:

list1 = []
list1.__getitem__(0) 

and then manipulate this item, BUTthat item does not exist since your made an empty list.

然后操作此项目,该项目不存在,因为您创建了一个空列表。

Proof of concept:

概念证明:

list1 = []
list1[1]
IndexError: list index out of range

We can, however, append new stuffto this list like so:

但是,我们可以像这样将新内容附加到此列表中:

list1 = []
for i in range(5):
    list1.append(i * 2)