Python常见数据类型转换操作示例
本文实例讲述了Python常见数据类型转换操作。分享给大家供大家参考,具体如下:
类型转换
主要针对几种存储工具:list、tuple、dict、set
特殊之处:dict是用来存储键值对的。
1、list 转换为set
l1 = [1, 2, 4, 5] s1 = set(l1) print(type(s1)) print(s1)
输出:
<class 'set'>
{1, 2, 4, 5}
2、set转换为list
s1 = set([1, 2, 3, 4]) l1 = list(s1) print(type(l1)) print(l1)
输出:
<class 'list'>
[1, 2, 3, 4]
3、tuple 转换为set
t1 = (1, 2, 3, 4) s1 = set(t1) print(type(s1)) print(s1)
输出:
<class 'set'>
{1, 2, 3, 4}
4、set转换为tuple
s1 = set([1, 2, 3, 4]) t1 = tuple(s1) print(type(t1)) print(t1)
输出:
<class 'tuple'>
(1, 2, 3, 4)
5、list转tuple
l1 = [1, 2, 4, 5] t1 = tuple(l1) print(type(t1)) print(t1)
输出:
<class 'tuple'>
(1, 2, 4, 5)
6、tuple转list
t1 = (1, 2, 3, 4) l1 = list(t1) print(type(l1)) print(l1)
输出:
<class 'list'>
[1, 2, 3, 4]
7、list转dict
list1=[('a',1),('b',2),('c',3)] dict1={k:v for k,v in list1} dict2={v:k for k,v in list1} print(dict1) print(dict2)
输出:
{'a': 1, 'b': 2, 'c': 3}
{1: 'a', 2: 'b', 3: 'c'}
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
相关推荐
taiyangshenniao 2020-10-05
flycony 2020-09-23
jacktangj 2020-09-18
YENCSDN 2020-09-15
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
世事一场大梦 2020-11-17
xiaoseyihe 2020-11-16
Morelia 2020-11-03
CloudXli 2020-11-03
文山羊 2020-10-31
comtop0 2020-10-31
pythonxuexi 2020-10-30