我在Python 2.7.3中遇到语法错误,如下所示:
[s += 'Orig' for s in strs]
File "<stdin>", line 1
[s += 'Orig' for s in strs]
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
其中strs只是一个字符串列表,比如 ['a', 'b', 'c', 'd']
如果我将代码更改为:
[s + 'Orig' for s in strs]
Run Code Online (Sandbox Code Playgroud)
然后它工作:
['aOrig', 'bOrig', 'cOrig', 'dOrig']
Run Code Online (Sandbox Code Playgroud)
这背后的原因是什么?是因为列表理解中的s不可变吗?但它应该是一个暂时的对象,无论如何都会被丢弃,为什么不呢?
另外,做我想做的最有效的方法是什么?我查看了另一个链接:http://www.skymind.com/~ocrow/python_string/并尝试使用join,但是join并没有做我想要的事情; 它将字符串列表连接成一个字符串,而我想将一个字符串附加到字符串列表中.
你不能这样做.s += 'Orig'是简写s = s + Orig,这是一项任务.为清楚起见,python不允许您将赋值语句放在其他语句中.请参阅为什么我不能在表达式中使用赋值?在Python FAQ中了解更多详细信息.
| 归档时间: |
|
| 查看次数: |
879 次 |
| 最近记录: |