Python的集合(set)和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素
python 集合常用方法
(1)set
(2)update
(3)add
(4)remove
删除元素不存在会报错 可使用discard()
列表、元组、集合、字典相互转换
列表元组转其他
# 列表转集合(去重) l
ist1 = [6, 7, 7, 8, 8, 9]
set(list1)
# {6, 7, 8, 9}
#两个列表转字典
list1 = [‘key1‘,‘key2‘,‘key3‘]
list2 = [‘1‘,‘2‘,‘3‘]
dict(zip(list1,list2))
# {‘key1‘: ‘1‘, ‘key2‘: ‘2‘, ‘key3‘: ‘3‘}
#嵌套列表转字典
list3 = [[‘key1‘,‘value1‘],[‘key2‘,‘value2‘],[‘key3‘,‘value3‘]]
dict(list3)
# {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘, ‘key3‘: ‘value3‘}
# 列表、元组转字符串
list2 = [‘a‘, ‘a‘, ‘b‘]
‘‘.join(list2)
# ‘aab‘
tup1 = (‘a‘, ‘a‘, ‘b‘)
‘‘.join(tup1)
# ‘aab‘
字典转其他
# 字典转换为字符串
dic1 = {‘a‘:1,‘b‘:2}
str(dic1)
# "{‘a‘: 1, ‘b‘: 2}"
# 字典key和value互转
dic2 = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}
{value:key for key, value in a_dict.items()}
# {1: ‘a‘, 2: ‘b‘, 3: ‘c‘}
字符串转其他
# 字符串转列表
s = ‘aabbcc‘
list(s)
# [‘a‘, ‘a‘, ‘b‘, ‘b‘, ‘c‘, ‘c‘]
# 字符串转元组
tuple(s)
# (‘a‘, ‘a‘, ‘b‘, ‘b‘, ‘c‘, ‘c‘)
# 字符串转集合
set(s)
# {‘a‘, ‘b‘, ‘c‘}
# 字符串转字典
dic2 = eval("{‘name‘:‘ljq‘, ‘age‘:24}")
# 切分字符串 a = ‘a b c‘
a.split(‘ ‘)
# [‘a‘, ‘b‘, ‘c‘]
原文地址:https://www.cnblogs.com/lq0310/p/9135397.html