2

I get a syntax error in Python 2.7.3 like so:

[s += 'Orig' for s in strs]
  File "<stdin>", line 1
    [s += 'Orig' for s in strs]
        ^
SyntaxError: invalid syntax

where strs is just a list of strings, like ['a', 'b', 'c', 'd']

if I change the code to:

[s + 'Orig' for s in strs]

Then it works:

['aOrig', 'bOrig', 'cOrig', 'dOrig']

What's the reason behind this? Is it because the s in the list comprehension is not mutable? But it should be a temporary object that is discarded later anyway, so why not?

Also, what is the most efficient way to do what I want to do? I looked at another link: http://www.skymind.com/~ocrow/python_string/ and tried to use join, but join does not do what I want; it joins a list of strings into a single string, whereas I want to append a string to a list of strings.

4

4 に答える 4

7

Assignment in Python (including +=) is a statement, not an expression. You can only use expressions in a list comprehension.

What does your example with + not do that you want it to do?

于 2012-06-15T21:34:26.840 に答える
7

You can't do this. s += 'Orig' is shorthand for s = s + Orig, which is an assignment. For clarity reasons, python does not allow you place assignment statements inside other statements. See the Why can’t I use an assignment in an expression? in the Python FAQ for more details.

于 2012-06-15T21:36:53.457 に答える
2

Well, you could do

strs = [s+'Orig' for s in strs]

or

strs = map(lambda s: s+'Orig', strs)

I find the list comprehension (the first one) easier to read.

于 2012-06-15T21:46:19.737 に答える
0

You cant use it as an expression. Only through an assignment in a statement can the (+=) symbol be used.

于 2012-06-15T21:35:21.807 に答える