python list of numbers converted to string incorrectly

前端 未结 4 1036
悲&欢浪女
悲&欢浪女 2020-12-20 17:28

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

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


        
相关标签:
4条回答
  • 2020-12-20 17:35

    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.

    0 讨论(0)
  • 2020-12-20 17:36

    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.

    0 讨论(0)
  • 2020-12-20 17:46

    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)
    
    0 讨论(0)
  • 2020-12-20 17:54

    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']
    
    0 讨论(0)
提交回复
热议问题