python-3.x - 为什么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 中,一切都是被视为引用的对象。
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
推荐阅读
- string - 如何构建一个非常健壮的 PLSQL 日期解析函数?
- aws-sam - 错误:无法创建托管资源:无法找到凭据(sam deploy --guided)
- javascript - 如何在运行时访问 JSDoc
- html - 具有 3 种水平颜色的网站正文背景
- npm - npm 和 webpack - 包大小
- flutter - 需要从 Google Places API 中获取评级数字,而不仅仅是星星
- sql - 试图总结 2 个表,其中某些条目在另一个表中不存在
- python - 我怎么能用 BeautifulSoup 分割这个?
- react-native - 在 React Native Expo 中更新状态变量
- list - Flutter ListView删除项目不起作用