python list of numbers converted to string incorrectly

前端 未结 4 1064
悲&欢浪女
悲&欢浪女 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: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)
    

提交回复
热议问题