python列表、元组、集合及字典之间如何相互转换?

python列表、元组、集合及字典之间如何相互转换?

# -*- coding: UTF-8 -*-
"""
@author:AmoXiang
@file:2.列表、元组、集合及字典之间如何相互转换.py
@time:2020/11/10
"""
# 1.列表元组转换为其他类型
# 列表转集合(去重)
list1 = [6, 7, 7, 8, 8, 9]
print(set(list1))  # {8, 9, 6, 7}
# 两个列表转字典
list1 = ['key1', 'key2', 'key3']
list2 = ['1', '2', '3']
print(dict(zip(list1, list2)))  # {'key1': '1', 'key2': '2', 'key3': '3'}
# 嵌套列表转字典
list3 = [['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3']]
# {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(dict(list3))
# 列表,元组转字符串
list2 = ['a', 'a', 'b']
print("".join(list2))  # aab
tuple1 = ('a', 'a', 'b')
print("".join(tuple1))  # aab
print("------------------------------------------------------------")
# 2.字典转换为其他类型
# 字典转换为其他类型
dic1 = {'a': 1, 'b': 2}
print(str(dic1))  # "{'a': 1, 'b': 2}"
print(type(str(dic1)))  # <class 'str'>
# 字典 key和value互转
dic2 = {'a': 1, 'b': 2, 'c': 3}
# {1: 'a', 2: 'b', 3: 'c'}
print({value: key for key, value in dic2.items()})
print("------------------------------------------------------------")
# 3.字符串转换为其他类型
# 字符串转列表
s = "aabbcc"
print(list(s))  # ['a', 'a', 'b', 'b', 'c', 'c']
# 字符串转元组
print(tuple(s))  # ('a', 'a', 'b', 'b', 'c', 'c')
# 字符串转集合
print(set(s))  # {'a', 'b', 'c'}
# 字符串转字典
dic2 = eval("{'name': 'Amo', 'age': 18}")
print(dic2)  # {'name': 'Amo', 'age': 18}
print(type(dic2))  # <class 'dict'>
# 切分字符串
a = "a b c"
print(a.split(' '))  # ['a', 'b', 'c']

分享到 :
相关推荐

Leave a Reply

Your email address will not be published. Required fields are marked *