循环中列表项的修改(python)
我尝试使用 for 循环修改列表中的项目,但出现错误(见下文)。示例代码:
#!/usr/bin/env python
# *-* coding: utf8 *-*
data = []
data.append("some")
data.append("example")
data.append("data")
data.append("here")
for item in data:
data[item] = "everything"
错误:
Traceback (most recent call last):
File "./testy.py", line 11, in <module>
data[item] = "everything"
TypeError: list indices must be integers, not str
有什么办法解决这个问题吗?
I'm trying to modify items in a list using a for loop, but I get an error (see below). Sample code:
#!/usr/bin/env python
# *-* coding: utf8 *-*
data = []
data.append("some")
data.append("example")
data.append("data")
data.append("here")
for item in data:
data[item] = "everything"
Error:
Traceback (most recent call last):
File "./testy.py", line 11, in <module>
data[item] = "everything"
TypeError: list indices must be integers, not str
Is there any way to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
您遇到的基本问题是,当您编写
data[i]
时,data
是一个列表,i
需要是一个整数,列表中的数字索引。但在循环中item
是列表中的实际事物,即字符串,而不是事物的数字索引。xrange
是一个迭代器,它生成数字而不是列表中的值,因此您可以使用它。另一种选择是
enumerate
函数为您提供一个对(index, item)
形式的元组进行迭代的迭代器,因此您所需要做的就是获取索引并忘记物品。我不确定其中一种方式(enumerate
或xrange
)会明显更快或更好,因为我认为列表将其长度存储在变量中,这样它就可以无需计算列表元素即可快速访问。但是,如果您需要旧列表值来计算新列表值,
enumerate
方式可能会稍微快一些,因为您避免让 Python 查找列表中的元素:这种事情更好不过,表示为列表理解:
当您执行此操作时,Python 将遍历 data 中的每个项目,将函数应用于它,并自动从结果构造一个新列表,因此您不需要需要担心将 func(item) 的结果放在列表中的正确位置。你原来的例子实际上可以表达为
Try this instead:
The basic problem you're having is that when you write
data[i]
, withdata
being a list, thei
needs to be an integer, a numerical index into the list. But in the loopitem
is the actual thing that's in the list, i.e. a string, not the numerical index of the thing.xrange
is an iterator that produces numbers instead of the values in the list, so you can use that.An alternative would be
The
enumerate
function gives you an iterator over tuples of the form(index, item)
, so all you need to do is take the index and forget about the item. I'm not sure that one way or the other (enumerate
orxrange
) will be significantly faster or better, since I think lists store their length in a variable so it can be quickly accessed without counting through the list elements.However, if you need the old list value to compute the new list value, the
enumerate
way will probably be slightly faster because you avoid making Python look up the element in the list:This sort of thing is better expressed as a list comprehension, though:
When you do this, Python will go through each item in
data
, apply the function to it, and construct a new list from the results automatically, so you don't need to worry about putting the result offunc(item)
in the right place in the list. Your original example could actually be expressed as列表项通过整数索引访问,即在您的示例中
data[1] == 'example'
。这就是当您使用字符串作为查找时 Python 会抱怨的原因。如果您想通过值查找列表中的元素,可以使用 data.index("value") :
但如果您只想循环它们,请使用 enumerate()正如大卫建议的那样。
List items are accessed by integer index, i. e. in your example
data[1] == 'example'
. This is why Python complains when you're using a string as a lookup.If you want to find an element in a list by its value, you can use
data.index("value")
:But if you just want to loop over them, use
enumerate()
as David suggested.使用整数对列表进行索引可能效率低下。 python 很可能使用带有底层指针的链接表来存储列表元素。在这种情况下,要查找特定项目,Python 必须遍历列表,直到找到第 i 个项目。
建议使用这样的格式可能会更有效:
a[:] = [x*x 表示 a 中的 x]
the indexing of a list using integers could be inefficient. It is likely that python stores list elements using linked table with underlying pointers. In this case, to find a specific item, python have to traverse the list until the i-th item.
It is suggested that using the format like this could be efficient:
a[:] = [x*x for x in a]