如何在Python中重新分配列表中的项目? [英] How to re-assign items in a list in Python?

查看:418
本文介绍了如何在Python中重新分配列表中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python中重新分配列表中的每个项目。

I want to re-assign each item in a list in Python.

In [20]: l = [1,2,3,4,5]
In [21]: for i in l:
   ....:     i = i + 1
   ....:     
   ....:     

但是列表根本没有变化。

But the list didn't change at all.

In [22]: l
Out[22]: [1, 2, 3, 4, 5]

我想知道为什么会这样。任何机构都可以详细解释列表吗?谢谢。

I want to know why this happened. Could any body explain the list iterating in detail? Thanks.

推荐答案

你不能这样做,你只是将绑定的值更改为名称。在 for 循环的每次迭代中, i 被绑定到列表中的值。它不是一个指针,通过更改 i 的值,您正在更改列表中的值。相反,正如我之前所说,它只是一个名称而你只是在改变名称所指的值。在这种情况下, i = i + 1 ,将 i 绑定到值 i + 1 。因此,您实际上并没有影响列表本身,要做到这一点,您必须通过索引进行设置。

You can't do it like that, you are merely changing the value binded to the name i. On each iteration of the for loop, i is binded to a value in the list. It is not a pointer in the sense that by changing the value of i you are changing a value in the list. Instead, as I said before, it is simply a name and you are just changing the value that name refers to. In this case, i = i + 1, binds i to the value i + 1. So you aren't actually affecting the list itself, to do that you have to set it by index.

>>> L = [1,2,3,4,5]
>>> for i in range(len(L)):
        L[i] = L[i] + 1

>>> L
[2, 3, 4, 5, 6]

有些pythonistas可能更喜欢迭代如下:

Some pythonistas may prefer to iterate like this:

for i, n in enumerate(L): # where i is the index, n is each number
    L[i] = n + 1

然而,您可以轻松地获得相同的结果列表理解:

However you can easily achieve the same result with a list comprehension:

>>> L = [1,2,3,4,5]
>>> L = [n + 1 for n in L]
>>> L
[2, 3, 4, 5, 6]

欲了解更多信息:< a href =http://www.effbot.org/zone/python-objects.htm =nofollow> http://www.effbot.org/zone/python-objects.htm

这篇关于如何在Python中重新分配列表中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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