Python has built-in dictionary support: dict. The full name of dict is dictionary. It is also called map in other languages. It uses key-value (key- value) storage, with extremely fast search speed.
Example: Suppose you want to find the corresponding grades based on the names of classmates. If you use a list to implement it, you need two lists:
names = ['Michael', 'Bob', 'Tracy'] scores = [95, 75, 85]
Define a name. To find the corresponding score, you must first find the corresponding position in names, and then retrieve the corresponding score from scores. The longer the list, the longer it takes.
If you use dict to implement it, you only need a "name"-"score" comparison table, and you can directly search for results based on the name. No matter how big the table is, the search speed will be very slow. will be slower.
Example:
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print(d['Michael'])
dict means to look up the page number corresponding to the word in the dictionary's index table (such as the radical table), and then turn directly to the page to find the word. No matter which word you are looking for, this search speed is very fast and will not slow down as the size of the dictionary increases.
The method of putting data into dict, in addition to specifying it during initialization, can also be put in by key:
d['Adam'] = 67 print(d['Adam'])
由于一个key只能对应一个value,所以,多次对一个key放入value,后面的值会把前面的值冲掉:
d['Jack'] = 90 d['Jack'] = 88 print(d['Jack']) #多次对一个key放入value,后面的值会把前面的值冲掉:显示后面修改的值
如果key不存在,dict就会报错:
print( d['Thomas'])
print('Thomas' in d)
d.get('Thomas') print(d.get('Thomas', -1))
注:
返回None的时候Python的交互式命令行不显示结果。
要删除一个key,用pop(key)方法,对应的value也会从dict中删除:
d.pop('Bob') print(d)
查找和插入的速度极快,不会随着key的增加而增加;
需要占用大量的内存,内存浪费多。而list相反:
查找和插入的时间随着元素的增加而增加;
占用空间小,浪费内存很少。所以,dict是用空间来换取时间的一种方法。
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
要创建一个set,需要提供一个list作为输入集合:
s = set([1, 2, 3]) print(s)
传入的参数[1, 2, 3]是一个list,而显示的{1, 2, 3}只是告诉这个set内部有1,2,3这3个元素,显示的顺序也不表示set是有序的。。
重复元素在set中自动被过滤:
s = set([1, 1, 2, 2, 3, 3]) print(s)
通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果:
s.add(4) s{1, 2, 3, 4}
通过remove(key)方法可以删除元素:
s.remove(2) print(s)
set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作:
s1 = set([1, 2, 3]) s2 = set([2, 3, 4]) print(s1 & s2) print(s1 | s2)
仅在于没有存储对应的value,但是,set的原理和dict一样,所以,同样不可以放入可变对象,因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”。试试把list放入set,看看是否会报错。
str是不变对象,而list是可变对象。对于可变对象,比如list,对list进行操作,list内部的内容是会变化的。
例:
a = ['c', 'b', 'a'] a.sort() # a['a', 'b', 'c'] print(a)
而对于不可变对象,比如str,对str进行操作呢:
a = 'abc' b = a.replace('a', 'A') print(b) print(a)
注:
对于不变对象来说,调用对象自身的任意方法,也不会改变该对象自身的内容。相反,这些方法会创建新的对象并返回,这样,就保证了不可变对象本身永远是不可变的。
本文基于Python基础,介绍了如何去使用dict和set, 使用key-value存储结构的dict在Python中非常有用,选择不可变对象作为key很重要,最常用的key是字符串。
The above is the detailed content of Inventory of common uses of dict and set in Python programming. For more information, please follow other related articles on the PHP Chinese website!