为什么一个循环会修改列表列表,而另一个则不会 [英] Why will one loop modify a list of lists, but the other won't

查看:61
本文介绍了为什么一个循环会修改列表列表,而另一个则不会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

告诉我,我的理解甚至超出了我的想象.

One of the answers in "python way" to parse and conditionally replace every element in 2D list has revealed to me that I understand even less than I thought.

给出包含字符串的列表列表:

Given a list of lists containing strings:

myLists = [['5','cat','23'], 
           ['33','parakeet','scalpel'], 
           ['correct','horse','battery','staple','99']]  

我希望将每个元素替换为:

I wish to replace each element with the return of:

def numParser(string):
    try:
        return int(string)
    except ValueError:
        return string

我的原始代码是这样,但它不会修改原始数组.我认为是因为list是副本,而不是实际列表(我错了吗?):

My original code was this, but it does not modify the original array. I assumed because list is a copy, not the actual list (am I wrong?):

for single_list in myLists:
    single_list = map(numParser, rawData)

修改位置列表的答案之一是:

And one of the answers which modifies the lists in place is:

for single_list in myLists:
    for i, item in enumerate(single_list):
        single_list[i] = numParser(item)

为什么第二个解决方案有效,但第一个解决方案无效?

Why does the second solution work but not the first?

推荐答案

此语句:

single_list = ...

为名为single_list的局部变量分配一个值.它对任何其他数据都没有影响.

assigns a value to the local variable named single_list. It does not have any effect on any other data.

声明:

single_list[i] = ...

修改名为single_list的局部变量引用的对象的值,特别是它设置列表中特定元素的值.

modifies the value of the object referenced by the local variable named single_list, specifically it sets the value of a particular element of the list.

这篇关于为什么一个循环会修改列表列表,而另一个则不会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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