本文实例讲述了python常见数据类型转换操作。分享给大家供大家参考,具体如下:
类型转换
主要针对几种存储工具:list、tuple、dict、set
特殊之处:dict是用来存储键值对的。
1、list 转换为set
1
2
3
4
|
l1 = [ 1 , 2 , 4 , 5 ]
s1 = set (l1)
print ( type (s1))
print (s1)
|
输出:
<class 'set'>
{1, 2, 4, 5}
2、set转换为list
1
2
3
4
|
s1 = set ([ 1 , 2 , 3 , 4 ])
l1 = list (s1)
print ( type (l1))
print (l1)
|
输出:
<class 'list'>
[1, 2, 3, 4]
3、tuple 转换为set
1
2
3
4
|
t1 = ( 1 , 2 , 3 , 4 )
s1 = set (t1)
print ( type (s1))
print (s1)
|
输出:
<class 'set'>
{1, 2, 3, 4}
4、set转换为tuple
1
2
3
4
|
s1 = set ([ 1 , 2 , 3 , 4 ])
t1 = tuple (s1)
print ( type (t1))
print (t1)
|
输出:
<class 'tuple'>
(1, 2, 3, 4)
5、list转tuple
1
2
3
4
|
l1 = [ 1 , 2 , 4 , 5 ]
t1 = tuple (l1)
print ( type (t1))
print (t1)
|
输出:
<class 'tuple'>
(1, 2, 4, 5)
6、tuple转list
1
2
3
4
|
t1 = ( 1 , 2 , 3 , 4 )
l1 = list (t1)
print ( type (l1))
print (l1)
|
输出:
<class 'list'>
[1, 2, 3, 4]
7、list转dict
1
2
3
4
5
|
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程序设计有所帮助。
原文链接:https://blog.csdn.net/lm_is_dc/article/details/80077304