简体   繁体   中英

python list of numbers converted to string incorrectly

For some reason, when I do the code...

def encode():
    result2 = []
    print result  
    for x in result:  
        result2 += str(x)  
    print result2

I get...

[123, 456, 789]
['1', '2', '3', '4', '5', '6', '7', '8', '9']

How do I get it to return ['123', '456', '789'] ?

Thanks!

How about:

result2 = [str(x) for x in result]

The reason you are getting what you are getting is the += is doing list concatenation. Since str(123) is '123' , which can be seen as ['1', '2', '3'] , when you concatenate that to the empty list you get ['1', '2', '3'] (same thing for the other values).

For it to work doing it your way, you'd need:

result2.append(str(x)) # instead of result2 += str(x)

The problem is that when you use += on a list, it expects the thing on the other side of the operator to be a list or some other kind of iterable. So you could do this:

>>> def encode():
...     result2 = []
...     print result 
...     for x in result: 
...         result2 += [str(x)]
...     print result2
... 
>>> result = [123, 456, 789]
>>> encode()
[123, 456, 789]
['123', '456', '789']

But when you do this:

result2 += str(x)

Python assumes you meant to treat the result of str(x) as an iterable, so before extending result2 , it effectively* converts the string into a list of characters, as in the below example:

>>> [list(str(x)) for x in result]
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

As NullUserException suggested, a quick way to convert the items in a list is to use a list comprehension. In this case, just remove the list call above.


*To be precise, it converts the result of str(x) to an iterator (as by calling iter() -- or, as eryksun pointed out, by calling the the corresponding C API function PyObject_GetIter , though of course that only applies to cpython). Since iteration over a string is actually iteration over the individual characters in the string, each character gets added to the list separately.

The functional method is to use list(map(str, lst)) :

lst = [123, 456, 789]

res = list(map(str,  lst))

print(res)
# ['123', '456', '789']

Performance is slightly better than a list comprehension.

Using map http://docs.python.org/library/functions.html#map

In [2]: input_list = [123, 456, 789]
In [3]: output_list = map(lambda x:str(x), input_list)
In [4]: output_list
Out[5]: ['123', '456', '789']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM