python数字列表错误地转换为字符串 [英] python list of numbers converted to string incorrectly

查看:75
本文介绍了python数字列表错误地转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,当我编写代码时...

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

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

我知道...

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

如何获取返回['123', '456', '789']的信息?

谢谢!

推荐答案

怎么样:

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

获得结果的原因是+=正在执行列表串联.由于str(123)'123',可以看作是['1', '2', '3'],因此当您将其连接到空列表时,将得到['1', '2', '3'](其他值也是如此).

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)

这篇关于python数字列表错误地转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆