python 中数据类型之间的转换

## 元组转列表转元组
'''
>>> name = ('a', 'b', 'c')
>>> list1 = list(name)
>>> list1
['a', 'b', 'c']
>>> tuple1 = tuple(list1)
>>> tuple1
('a', 'b', 'c')
'''
----------------------------------------------------------------------------------------------

##字典转元组转字典
'''
>>> dic1 = {'name':'tom', 'score':90, 'age':23}
>>> tuple2 = tuple(dic1)
>>> tuple2
('name', 'score', 'age')
>>> tuple2 = tuple(dic1.items())
>>> tuple2
(('name', 'tom'), ('score', 90), ('age', 23))
>>> dic1 = dict(tuple2)
>>> dic1
{'name': 'tom', 'score': 90, 'age': 23}
>>>
'''
-----------------------------------------------------------------------------------------------

##字典转列表转字典
'''
>>> dic2 = {'name':'tan', 'score':89, 'age':23}
>>> list1 = list(dic2)
>>> list1
['name', 'score', 'age']
>>> list1 = list(dic2.items())
>>> list1
[('name', 'tan'), ('score', 89), ('age', 23)]
>>> dic2 = dic(list1)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
dic2 = dic(list1)
NameError: name 'dic' is not defined
>>> dic2 = dict(list1)
>>> dic2
{'name': 'tan', 'score': 89, 'age': 23}

'''
----------------------------------------------------------------------------------------------

##转字典的特殊方法
1)通过dic(元组中的变量)
'''
>>> tuple2 = (name = 'tom', score = 90, age = 23) #企图定义一个元组但是很显然不符合语法规范
SyntaxError: invalid syntax
>>> dic2 = dict(a = 1, b = 2, c = 3)
>>> dic2
{'a': 1, 'b': 2, 'c': 3}
>>> a = 1
>>> b = 2
>>> c = 3
>>> dic2 = dict(a, b, c) #体现出了字典的键值关系
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
dic2 = dict(a, b, c)
TypeError: dict expected at most 1 arguments, got 3
'''

2)通过自带的方法 dic.fromkeys([key1], [key2], [key3])
'''
>>> list3 = ['name', 'score', 'age']
>>> dic3 = dict.fromkeys(list3)
>>> dic3
{'name': None, 'score': None, 'age': None} #默认返回键的值问为None
>>>
'''

'''
>>> dic3 = dict.fromkeys(['name', 'score', 'age'])
>>> dic3
{'name': None, 'score': None, 'age': None}
,,,

转载于:https://www.cnblogs.com/pontoon/p/8503560.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值