循环中列表项的修改(python) [英] Modification of the list items in the loop (python)

查看:129
本文介绍了循环中列表项的修改(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用for循环修改列表中的项目,但出现错误(请参见下文).示例代码:

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"

错误:

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?

推荐答案

尝试以下方法:

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

您遇到的基本问题是,当您编写data[i]时,以data作为列表,i必须是整数,并且是列表中的数字索引.但是在循环中

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是列表中的实际事物,即字符串,而不是事物的数字索引. xrange是一个迭代器,它生成数字而不是列表中的值,因此您可以使用它.

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.

另一种选择是

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

enumerate函数为您提供了对(index, item)形式的元组的迭代器,因此您所需要做的就是获取索引,而忽略该项目.我不确定一种或另一种方式(enumeratexrange)是否会明显更快或更佳,因为我认为列表将其长度存储在变量中,因此可以快速访问它而无需计算列表元素.

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.

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

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]

执行此操作时,Python将遍历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]

这篇关于循环中列表项的修改(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆