常见的 Python 数据类型相互转换
Python 常用数据类型转换,包含字符串str、列表list、集合set、字典dict、元组tuple、数字num等。
主要转换方式如下表所示:
转换方向 -->> |
元组(,) |
字符串“” |
数字123 |
列表[] |
集合{} |
字典{"":""} |
元组(,) |
/ |
N="".join(item for item in tuple) |
N=int("".join(item for item in tuple)) |
L=list(tuple) |
S=set(tuple) |
D={key:value for key,value in enumerate(tuple)} |
字符串 “” |
T=tuple(str) |
/ |
N=int(str)
|
L=list(str) |
S=set(str) |
D=eval(str) / D={key:value for key,value in enumerate(str)} |
数字123 |
T=tuple([num]) |
S=str(num) |
/ |
L=[int(item) for item in str(num)] |
S= set(str(num)) |
D={key:value for key,value in enumerate(str(num))} |
列表[] |
T=tuple(list) |
S=””.join(list) / list2=[str(item) for item in list] S="".join(list2) |
N=int("".join(str(item) for item in list)) |
/ |
S=set(list) |
D={key:value for key,value in enumerate(list)} (单列表) / nvs = zip(list1, list2) nvDict = dict((key, value) for list1, list2 in nvs) (两列表) |
集合{} |
T=tuple(set) |
S="".join(str(item) for item in set) |
N=int("".join(str(item) for item in set))
|
L=list(set) |
/ |
D={key:value for key,value in enumerate(set)} |
字典{“”:””} |
T=tuple(dict) / T=tuple(dict.values()) |
S=str(dict) / S= "".join(key for key in dict.keys()) / S="".join(key for key in dict.values()) |
N= int("".join(key for key in dict.keys())) |
L=list(key for key in dict.keys()) / L=list(key for key in dict.values()) |
/ |
/ |
其中,字符串转字典类型,若字符串格式特殊,类似json类型,可直接通过eval()函数操作,如下:
# 字符串转字典
str = "123"
print({key: value for key, value in enumerate(str)}) # {0: '1', 1: '2', 2: '3'}
str = "{0: '1', 1: '2', 2: '3'}"
dic = eval(str)
print(dic) # {0: '1', 1: '2', 2: '3'}
列表转字符串类型,简单的情况只包含字符串或数字类型,特殊列表需具体分析。
# 列表转字符串:
list1 = ["1", "2", "3"]
s = ''.join(list1)
print(s, s.__class__)
list1 = [1, 2, 3]
list2 = [str(item) for item in list1]
S = "".join(list2)
print(S, S.__class__)
字典类型转换为其他类型时较为繁琐,且情况多样,在此只列举简单的dict.keys()与dict.values()作为主要转换内容。
总结:
python 中涉及序列对象(str, tuple, list)之间的转换较为简单,str(), tuple(), list() 方法直接转换 或 间接拼接转换;
int() 方法操作的对象为非迭代对象,即 'int' object is not iterable 错误,此时可将对象转换为字符串 str 后再调用 int() 方法;
'str' object is not callable 错误:主要表现在上下文中使用 str 去命名变量或作为参数等,这与python 的内建函数 str() 命名方法冲突,须重命名变量 str 即可。