Python类型转换 [英] Python Type Conversion

查看:115
本文介绍了Python类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是在python中将int,long,double转换为字符串的最佳方法,反之亦然。

Whats the best way to convert int's, long's, double's to strings and vice versa in python.

我循环遍历列表并将long传递给dict应该变成一个unicode字符串。

I am looping through a list and passing longs to a dict that should be turned into a unicode string.

我做

for n in l:  
    {'my_key':n[0],'my_other_key':n[1]}

为什么一些最明显的事情如此复杂?

Why are some of the most obvious things so complicated?

推荐答案

你可以在Python中这样做2.x:

You could do it like this in Python 2.x:

>>> l = ((1,2),(3,4))
>>> dict(map(lambda n: (n[0], unicode(n[1])), l))
{1: u'2', 3: u'4'}

或在Python 3.x中:

or in Python 3.x:

>>> l = ((1,2),(3,4))
>>> {n[0] : str(n[1]) for n in l}
{1: '2', 3: '4'}

请注意,Python 3中的字符串与Python 2中的unicode字符串相同。

Note that strings in Python 3 are the same as unicode strings in Python 2.

这篇关于Python类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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