首页 > 解决方案 > 为什么python3 for循环不覆盖变量?

问题描述

对于初学者类型的问题,但有人可以告诉我为什么 python 3 不会覆盖这一行中的以下变量 output = output + s1/output = output + s2

简而言之,任何人都可以告诉 this==>output = output + s2 的内部工作原理,它是否获得了 assign ref 变量?或将价值存储在其中?

s=input("enter your string: ") #A132BC
S1='' 
S2=''
output=''
for x in s: 
    if x.isalpha():
        S1=S1 + x 
    else:
        S2=S2 + x 
for s1 in sorted(S1): 
    output = output + s1 #output = '' + A==>  output = 'A'
for s2 in sorted(S2):
    output = output + s2
print(output)

标签: python-3.x

解决方案


在 Python 中,一切都是被视为引用的对象。

S1 = ""创建值""并将引用存储到 nameS1中。如果稍后您这样做S1 = "Hello, world!,解释器会创建一个新值并将这个新引用分配给S1.

发生相同的行为output,首先它存储对 "" 的引用,当您执行output = output + s1一个新值时,output即创建 s1 和 s1 的连接并将新引用分配给output

并不是说这可以用更简洁的方式写成output += s1.

链接包含有关 Python 类型分配的有用信息。


笔记

正如评论中所指出的,分配有一些微妙之处,您可以阅读 [this](但是,我将更新我的答案,关于关于可变/不可变行为的缺失说明。)博客文章以获取更多详细信息。

对初学者指出的一个有趣且颇具误导性的行为是 operator 的使用存在差异+=。对于 int、str 或 bool,此运算符有效地从旧值创建一个新值,原始值不会发生变化。对于序列,此运算符的行为具有变异运算符。

例如比较这两个函数的输出:

def modify(int_value):
  int_value += 1  # Does not add 1 in-place

def modify(array):
  array += [1]  # Mutates the array in-place

推荐阅读