Python:为什么这段代码失败了?将变量分配给for循环中的自身列表

时间:2017-06-28 03:05:14

标签: python variables reference variable-assignment immutability

a = 'hello'
b = None
c = None
for x in [a, b, c]:
    if isinstance(x, (basestring, dict, int, float)) or x is None:
        x = [x]
a

返回'hello',但预期['hello']。但是,这有效:

a = 'hello'
a = [a]
a

返回['hello']

3 个答案:

答案 0 :(得分:4)

要实现这一点,首先你必须明白你有两个不同的结果,a和x(对于每个元素),以及列表[a,b,c]的引用,仅在for循环中使用,以及永远不会更多。

要实现目标,您可以这样做:

a = 'hello'
b = None
c = None
lst = [a, b, c] #here I create a reference for a list containing the three references above
for i,x in enumerate(lst):
    if isinstance(x, (str,dict, int, float)) or x is None: #here I used str instead basestring
        lst[i] = [x]

print(lst[0]) #here I print the reference inside the list, that's why the value is now showed modified
  

[ '你好']

但正如我所说,如果你打印(a)它会再次显示:

  

'你好'#我打印了变量a的值,没有修改

因为你从未做过任何事情。

请查看此问题,了解有关参考How do I pass a variable by reference?

的更多信息

答案 1 :(得分:3)

让我们一次完成这一行;

a = 'hello'  # assigns 'hello' to a.
b = None  # etc...
c = None
for x in [a, b, c]:  # Creates list from the values in 'a' 'b' and 'c', then iterates over them.
    # This if statement is always True. x is always either a string, or None.
    if isinstance(x, (basestring, dict, int, float)) or x is None:
        x = [x]  # On the first iteration, sets variable to the expected ['hello']
        # After that though - it replaces it with [None]
a  # = 'hello' - you have not assigned anything to the variable except on the first line.

唯一设置为['hello']的变量是x,它会被None快速覆盖。如果您更改了if检查以排除or x is None并分配到a而不是x,那么您将获得所需的结果。

还值得注意的是,启动for循环时会创建列表[a, b, c]。在for循环期间更改a bc将不起作用 - 列表已经创建。

答案 2 :(得分:0)

其他答案很棒。我认为,概括来说,list元素是不可变的/可散列的,因此for循环返回一个副本,而不是对原始对象的引用。我应该发现这一点,但教我编码太长时间没有睡觉!

我最终使用了这个:

def lst(x):
    if isinstance(x, (basestring, dict, int, float)) or x is None:
        x = [x]
    return x
[a, b, c] = map(lst, [a, b, c])