循环中列表项的修改(python)

发布于 2024-09-07 23:47:03 字数 481 浏览 4 评论 0原文

我尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小霸王臭丫头 2024-09-14 23:47:03

试试这个:

for i in xrange(len(data)):
    data[i] = "everything"

您遇到的基本问题是,当您编写 data[i] 时,data 是一个列表,i需要是一个整数,列表中的数字索引。但在循环中

for item in data

item 是列表中的实际事物,即字符串,而不是事物的数字索引。 xrange 是一个迭代器,它生成数字而不是列表中的值,因此您可以使用它。

另一种选择是

for i, _ in enumerate(data):
    data[i] = "everything"

enumerate 函数为您提供一个对 (index, item) 形式的元组进行迭代的迭代器,因此您所需要做的就是获取索引并忘记物品。我不确定其中一种方式(enumeratexrange)会明显更快或更好,因为我认为列表将其长度存储在变量中,这样它就可以无需计算列表元素即可快速访问。

但是,如果您需要旧列表值来计算新列表值,enumerate 方式可能会稍微快一些,因为您避免让 Python 查找列表中的元素:

for i, item in enumerate(data):
    data[i] = func(item)

这种事情更好不过,表示为列表理解:

data = [func(item) for item in data]

当您执行此操作时,Python 将遍历 data 中的每个项目,将函数应用于它,并自动从结果构造一个新列表,因此您不需要需要担心将 func(item) 的结果放在列表中的正确位置。你原来的例子实际上可以表达为

data = ["everything" for item in data]

Try this instead:

for i in xrange(len(data)):
    data[i] = "everything"

The basic problem you're having is that when you write data[i], with data being a list, the i needs to be an integer, a numerical index into the list. But in the loop

for item in data

item 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

for i, _ in enumerate(data):
    data[i] = "everything"

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 or xrange) 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:

for i, item in enumerate(data):
    data[i] = func(item)

This sort of thing is better expressed as a list comprehension, though:

data = [func(item) for item in data]

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 of func(item) in the right place in the list. Your original example could actually be expressed as

data = ["everything" for item in data]
疯到世界奔溃 2024-09-14 23:47:03

列表项通过整数索引访问,即在您的示例中 data[1] == 'example'。这就是当您使用字符串作为查找时 Python 会抱怨的原因。

如果您想通过值查找列表中的元素,可以使用 data.index("value") :

data[data.index("some")] = "something else"

但如果您只想循环它们,请使用 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"):

data[data.index("some")] = "something else"

But if you just want to loop over them, use enumerate() as David suggested.

冷月断魂刀 2024-09-14 23:47:03

使用整数对列表进行索引可能效率低下。 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]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文