python列表和字典(Python中字典与集合的使用指南)

全文共5092字,预计学习时长10分钟

python列表和字典(Python中字典与集合的使用指南)(1)

本文将介绍Python的内置集合模块,用于支持集合和键值对等数学概念。

python列表和字典(Python中字典与集合的使用指南)(2)

什么是集合?

集合是一组用于储存唯一值的序列。

初始化

可使用花括号{}定义集合。

>>> numSet = {1, 2, 3, 4, 5}

>>> print(numSet)

{1, 2, 3, 4, 5}

若在初始化中键入重复值,则只保留一个元素。

>>> numSet = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5}

>>> print(numSet)

{1, 2, 3, 4, 5}

也可使用内置的 set函数进行空集初始化。

>>> emptySet = set()

>>> print(emptySet)

set()

注意:集合元素是不可更改的,在集合中加入可变对象会报错。

>>> tuple1 = (1, 2, 3)

>>> tuple2 = (4, 5, 6)

>>> tupleSet = {tuple1, tuple2} # no error as tuples are immutable

>>> print(tupleSet)

{(4, 5, 6), (1, 2, 3)}

>>> list1 = [1, 2, 3]

>>> list2 = [4, 5, 6]

>>> listSet = {list1, list2} #will raise error as lists are mutable

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unhashable type: 'list'

加入元素

使用内置 add函数向集合中加入元素。

>>> numSet = {1, 2, 3, 4, 5}

>>> numSet.add(6)

>>> print(numSet)

{1, 2, 3, 4, 5, 6}

注意:在集合中加入重复元素是无效的,此情况下也不会报错。

>>> numSet = {1, 2, 3, 4, 5}

>>> numSet.add(5)

>>> print(numSet)

{1, 2, 3, 4, 5}

删除元素

使用内置remove函数删除集合中元素。

>>> numSet = {1, 2, 3, 4, 5}

>>> numSet.remove(5)

>>> print(numSet)

{1, 2, 3, 4}

注意:删除集合中不存在的元素不会报错。

>>> numSet = {1, 2, 3, 4, 5}

>>> numSet.remove(99)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

KeyError: 99

集合长度

使用内置len函数查找集合长度。

>>> numSet = {1, 2, 3, 4, 5}

>>> len(numSet)

5

查找

使用in运算符查找集合中元素。

>>> numSet = {1, 2, 3, 4, 5}

>>> 2 in numSet

True

>>> 99 in numSet

False

接下来介绍如何执行集合操作。

交集

使用 &运算符寻找两个集合的交集。

>>> setA = {1, 2, 3, 4, 5}

>>> setB = {3, 4, 5, 6, 7}

>>> intersection = setA & setB

>>> print(intersection)

{3, 4, 5}

并集

使用|运算符将两个集合合并。

>>> setA = {1, 2, 3, 4, 5}

>>> setB = {3, 4, 5, 6, 7}

>>> union = setA | setB

>>> print(union)

{1, 2, 3, 4, 5, 6, 7}

python列表和字典(Python中字典与集合的使用指南)(3)

补集

补集返回值为仅在第一个集合中出现的值。

使用-运算符寻找补集。

>>> setA = {1, 2, 3, 4, 5}

>>> setB = {3, 4, 5, 6, 7}

>>> difference = setA - setB

>>> print(difference)

{1, 2}

>>> reverseDifference = setB - setA

>>> print(reverseDifference)

{6, 7}

集合对称差

对称差返回值是由只属于两个集合中任一集合,而非全部集合的元素组成的集合。

使用 ^ 运算符寻找两个集合的对称差。

>>> setA = {1, 2, 3, 4, 5}

>>> setB = {3, 4, 5, 6, 7}

>>> symmDiff = setA ^ setB

>>> print(symmDiff)

{1, 2, 6, 7}

检查超集

若集合A含有集合B中所有元素,则集合A为集合B的超集。

使用>=运算符检验左侧集合是否为右侧集合的超集。

>>> bigSet = {1, 2, 3, 4, 5}

>>> smallSet = {3, 4}

>>> isSuperSet = bigSet >= smallSet

>>> print(isSuperSet)

True

使用<= 运算符检验右侧集合是否为左侧集合的超集。

>>> bigSet = {1, 2, 3, 4, 5}

>>> smallSet = {3, 4}

>>> isSuperSet = smallSet <= bigSet

>>> print(isSuperSet)

True

python列表和字典(Python中字典与集合的使用指南)(4)

如何使用字典?

python列表和字典(Python中字典与集合的使用指南)(5)

在Python中,字典用于储存键值对。

初始化

同样可以使用花括号{}初始化字典,并使用key :value 语法声明键值对。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> print(nameToNumber)

{'John': 1, 'Harry': 2, 'Jacob': 3}

也可使用内置dict函数初始化空字典。

>>> emptyDict = dict()

>>> print(emptyDict)

{}

还可直接使用空花括号{}初始化空字典。

>>> emptyDict = {}

>>> print(emptyDict)

{}

注意:不可改变字典中的键。尝试使用可变键创建字典会报错。

>>> tupleA = (1, 2, 3) # tuples are immutable

>>> stringA = "I love Python!" # strings are immutable

>>> floatA = 3.14 # float values are immutable

>>> dictA = {tupleA : True, stringA : False, floatA : True} # no error as all keys are immutable

>>> print(dictA)

{(1, 2, 3): True, 'I love Python!': False, 3.14: True}

>>> listB = [1, 2, 3] #list is mutable

>>> dictB = {listB : True} # raises an error as lists are mutable

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unhashable type: 'list'

获取数据

使用方括号([])从字典中获取键值。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> JohnsNumber = nameToNumber["John"]

>>> print(JohnsNumber)

1

注意:寻找不存在的键会报错。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> nameToNumber["Sam"]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

KeyError: 'Sam'

为避免报错,可以使用内置 get函数。使用该函数寻找不存在的键返回值为None,但不会报错。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> johnsNumber = nameToNumber.get("John")

>>> print(johnsNumber)

1

>>> samsNumber = nameToNumber.get("Sam"

>>> print(samsNumber)

None

若字典中缺少键,则可以使用get 函数返回默认值。将所需的默认值作为第二个参数传递给get 函数。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> johnsNumber = nameToNumber.get("John", 99)

>>> print(johnsNumber)

1

>>> samsNumber = nameToNumber.get("Sam", 99)

>>> print(samsNumber)

99

修改数据

使用内置setdefault 函数将数据插入字典。

只有在字典中不存在该键时,setdefault才会在字典中创建新键值对。若该键存在,也不会被覆盖。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> nameToNumber.setdefault("Sam", 4)

4

>>> print(nameToNumber)

{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 4}

>>> nameToNumber.setdefault("Sam", 99) # no changes as the key already exists

4

>>> print(nameToNumber)

{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 4}

使用内置update函数修改字典中现存值。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> nameToNumber.update({"Sam" : 4}) # creates new entry

>>> print(nameToNumber)

{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 4}

>>> nameToNumber.update({"Sam" : 99}) # updates existing entry

>>> print(nameToNumber)

{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 99}

也可使用方括号修改现存值。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> nameToNumber["Sam"] = 4 # creates new entry

>>> print(nameToNumber)

{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 4}

>>> nameToNumber["Sam"] = 99 # updates existing entry

>>> print(nameToNumber)

{'John': 1, 'Harry': 2, 'Jacob': 3, 'Sam': 99}

删除数据

使用 del命令删除字典中的键。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> del nameToNumber["John"]

>>> print(nameToNumber)

{'Harry': 2, 'Jacob': 3}

注意:删除不存在的键会报错。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> del nameToNumber["Sam"]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

KeyError: 'Sam'

迭代

使用内置keys功能在字典中的键上进行迭代。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> names = list(nameToNumber.keys()) # using list() to store in a list

>>> print(names)

['John', 'Harry', 'Jacob']

可以使用内置的values函数迭代字典中的值。

>>> nameToNumber = {"John" : 1, "Harry" : 2, "Jacob" : 3}

>>> values = list(nameToNumber.values())

>>> print(values)

[1, 2, 3]

python列表和字典(Python中字典与集合的使用指南)(6)

留言 点赞 关注

我们一起分享AI学习与发展的干货

如需转载,请后台留言,遵守转载规范

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页