赞
踩
list1 = [1, 2, 3, 4]
tuple1 = (5, 6, 7, 8)
set1 = {9, 10, 11, 12}
dict1 = {"a": "13", "b": "14", "c": "15", "d": "16"}
转为list
print(list(tuple1)) = [5, 6, 7, 8]
print(list(set1)) = [9, 10, 11, 12]
print(list(dict1)) = ['a', 'b', 'c', 'd']
转为tuple
print(tuple(list1)) = (1, 2, 3, 4)
print(tuple(set1)) = (9, 10, 11, 12)
print(tuple(dict1)) = ('a', 'b', 'c', 'd')
转为set(因为set是无序的集合,所以里面元素顺序会乱)
print(set(list1)) = {1, 2, 3, 4}
print(set(tuple1)) = {8, 5, 6, 7}
print(set(dict1)) = {'d', 'c', 'b', 'a'}
转为dict(三个都报错,字典是键值对存入)
print(dict(list1)) # 报错
print(dict(tuple1)) # 报错
print(dict(set1)) # 报错
(但是当list、set、tuple里面的元素是元组(列表),元组(列表)中的元素必须是2个,就能转为字典)
print(dict({(1, 2), (3, 4)})) = {1: 2, 3: 4}
print(dict(((1, 2), (3, 4)))) = {1: 2, 3: 4}
print(dict([(1, 2), (3, 4)])) = {1: 2, 3: 4}
总结
set、list、tuple 三种类型可以直接进行转化
将dict转为set/list/tuple,值只转换了key。
若将set、list、tuple 转为字典的时候,需要对set、list、tuple 要求高一些
必须set、tuple、list里面的元素必须是元组(列表),元组(列表)中的元素必须是2个,才能转为字典
eg:print(dict({(1, 2), (3, 4)})) ==== {1: 2, 3: 4}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。