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

查看:32
本文介绍了修改循环中的列表项(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 中的每一项,对其应用函数,并自动根据结果构造一个新列表,因此您无需担心将func(item) 的结果在列表中的正确位置.您的原始示例实际上可以表示为

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天全站免登陆