list 列表
转换为list 列表举例
''' int数字类型 是非容器类型,不能转换为list列表
str字符串 转换为列表时,会把字符串中的每一个字符当做列表的元素
set集合 可以转换为list列表类型
tuple元组 可以转换为list列表类型
dict字典 可以转换为list列表类型,但是只保留了字典中的键,值没有保留。 '''
n = '123' #str字符串课转
#n = 123 int数字不可转 #TypeError: 'int' object is not iterable
res = list(n)
print(n,type(n),res,type(res))
##输出结果为 123 <class 'str'> ['1', '2', '3'] <class 'list'>
n = {'a','b','c',1} #无序的集合可以转为list列表
res = list(n)
print(n,type(n),res,type(res))
##输出结果为 {'b', 'c', 'a', 1} <class 'set'> ['b', 'c', 'a', 1] <class 'list'>
n = (1,2,3,4) #元组可以转换为list列表
res = list(n)
print(n,type(n),res,type(res))
##输出结果为 (1, 2, 3, 4) <class 'tuple'> [1, 2, 3, 4] <class 'list'>
n = {'name':'zhangsan','age':'12'} #字典 可以转换为list列表
res = list(n)
print(n,type(n),res,type(res))
##输出结果为 {'name': 'zhangsan', 'age': '12'} <class 'dict'> ['name', 'age'] <class 'list'>
tuple 元组
''' int数字类型 是非容器类型,不能转换为tuple元组
list列表 可以转换为tuple元组类型
str字符串 转换为元组时,会把字符串中的每一个字符当做元组的元素
set集合 可以转换为tuple元组类型
dict字典 可以转换为tuple元组类型,但是只保留了字典中的键,值没有保留 '''
# m = 123
# res = tuple(m)
# print(m,type(m),res,type(res)) #输出结果为 TypeError: 'int' object is not iterable
# m = '12a3' #str字符串 可以转换为tuple 元组
# res = tuple(m)
# print(m,type(m),res,type(res)) #输出结果为 12a3 <class 'str'> ('1', '2', 'a', '3') <class 'tuple'>
# m = [1,2,'a',3] #list列表 可以转换为tuple 元组
# res = tuple(m)
# print(m,type(m),res,type(res)) #输出结果为 [1, 2, 'a', 3] <class 'list'> (1, 2, 'a', 3) <class 'tuple'>
# m = {1,2,'a',3} #set 集合 可以转换为tuple 元组
# res = tuple(m)
# print(m,type(m),res,type(res)) #输出结果为 {'a', 1, 2, 3} <class 'set'> ('a', 1, 2, 3) <class 'tuple'>
# m = {'name':'zhangsan','age':'12'} #字典 可以转换为tuple 元组
# res = tuple(m)
# print(m,type(m),res,type(res))
#输出结果为 {'name': 'zhangsan', 'age': '12'} <class 'dict'> ('name', 'age') <class 'tuple'>
set 集合
''' int数字类型 是非容器类型,不能转换为set 集合
字符串 可以转为 set集合 ,结果是无序的
list列表,tuple元组,都可以转为无序的set集合 dict字典,转换为集合时,只保留了字典的键(Key) '''
#此处不一一举例了,参见上述举例
dict 字典
''' int数字类型 是非容器类型,不能转换为dict 字典
str字符串类型 ,不能转换 dict 字典
list列表类型,可以转换 dict 字典 ,要求是一个二级(二维)列表,并且每个二级元素只能有两个值。
tuple元组,可以转换 dict 字典 ,要求是一个二级(二维)列表,并且每个二级元素只能有两个值。
set集合,可以转换 dict 字典 ,要求是一个二级(二维)列表,并且每个二级元素只能有两个值。 '''
例二级list列表转 dict字典
# n = [[1,2],['a','b']]
# res = dict(n)
# print(n,type(n),res,type(res))
#输出结果为 [[1, 2], ['a', 'b']] <class 'list'> {1: 2, 'a': 'b'} <class 'dict'>
#例:二级tuple元组 转dict字典
# n = ((1,2),(3,4))
# res = dict(n)
# print(n,type(n),res,type(res))
#输出结果为 ((1, 2), (3, 4)) <class 'tuple'> {1: 2, 3: 4} <class 'dict'>
# n = {{1,2},{3,4}}
# res = dict(n)
# print(n,type(n),res,type(res))
# #输出结果为 报错 TypeError: unhashable type: 'set'
#例:二级set集合,转为dict字典
# n = {(1,2),(3,4)}
# res = dict(n)
# print(n,type(n),res,type(res))
# #输出结果为 {(1, 2), (3, 4)} <class 'set'> {1: 2, 3: 4} <class 'dict'>