万字干货,Python语法大合集,一篇文章带你入门( 五 )


# "setdefault()" inserts into a dictionary only if the given key isn't presentfilled_dict.setdefault("five", 5)# filled_dict["five"] is set to 5filled_dict.setdefault("five", 6)# filled_dict["five"] is still 5复制代码我们可以使用update方法用另外一个dict来更新当前dict,比如a.update(b) 。对于a和b交集的key会被b覆盖,a当中不存在的key会被插入进来:
# Adding to a dictionaryfilled_dict.update({"four":4})# => {"one": 1, "two": 2, "three": 3, "four": 4}filled_dict["four"] = 4# another way to add to dict复制代码我们一样可以使用del删除dict当中的元素,同样只能传入key 。
Python3.5以上的版本支持使用**来解压一个dict:
{'a': 1, **{'b': 2}}# => {'a': 1, 'b': 2}{'a': 1, **{'a': 2}}# => {'a': 2}setset是用来存储不重复元素的容器,当中的元素都是不同的,相同的元素会被删除 。我们可以通过set(),或者通过{}来进行初始化 。注意当我们使用{}的时候,必须要传入数据,否则Python会将它和dict弄混 。
# Sets store ... well setsempty_set = set()# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry.some_set = {1, 1, 2, 2, 3, 4}# some_set is now {1, 2, 3, 4}复制代码set当中的元素也必须是不可变对象,因此list不能传入set 。
# Similar to keys of a dictionary, elements of a set have to be immutable.invalid_set = {[1], 1}# => Raises a TypeError: unhashable type: 'list'valid_set = {(1,), 1}复制代码可以调用add方法为set插入元素:
# Add one more item to the setfilled_set = some_setfilled_set.add(5)# filled_set is now {1, 2, 3, 4, 5}# Sets do not have duplicate elementsfilled_set.add(5)# it remains as before {1, 2, 3, 4, 5}复制代码set还可以被认为是集合,所以它还支持一些集合交叉并补的操作 。
# Do set intersection with &# 计算交集other_set = {3, 4, 5, 6}filled_set & other_set# => {3, 4, 5}# Do set union with |# 计算并集filled_set | other_set# => {1, 2, 3, 4, 5, 6}# Do set difference with -# 计算差集{1, 2, 3, 4} - {2, 3, 5}# => {1, 4}# Do set symmetric difference with ^# 这个有点特殊,计算对称集,也就是去掉重复元素剩下的内容{1, 2, 3, 4} ^ {2, 3, 5}# => {1, 4, 5}set还支持超集和子集的判断,我们可以用大于等于和小于等于号判断一个set是不是另一个的超集或子集:
# Check if set on the left is a superset of set on the right{1, 2} >= {1, 2, 3} # => False# Check if set on the left is a subset of set on the right{1, 2} <= {1, 2, 3} # => True复制代码和dict一样,我们可以使用in判断元素在不在set当中 。用copy可以拷贝一个set 。
# Check for existence in a set with in2 in filled_set# => True10 in filled_set# => False# Make a one layer deep copyfilled_set = some_set.copy()# filled_set is {1, 2, 3, 4, 5}filled_set is some_set# => False控制流和迭代判断语句Python当中的判断语句非常简单,并且Python不支持switch,所以即使是多个条件,我们也只能罗列if-else 。
# Let's just make a variablesome_var = 5# Here is an if statement. Indentation is significant in Python!# Convention is to use four spaces, not tabs.# This prints "some_var is smaller than 10"if some_var > 10:print("some_var is totally bigger than 10.")elif some_var < 10:# This elif clause is optional.print("some_var is smaller than 10.")else:# This is optional too.print("some_var is indeed 10.")复制代码循环我们可以用in来循环迭代一个list当中的内容,这也是Python当中基本的循环方式 。
"""For loops iterate over listsprints:dog is a mammalcat is a mammalmouse is a mammal"""for animal in ["dog", "cat", "mouse"]:# You can use format() to interpolate formatted stringsprint("{} is a mammal".format(animal))如果我们要循环一个范围,可以使用range 。range加上一个参数表示从0开始的序列,比如range(10),表示[0, 10)区间内的所有整数:
""""range(number)" returns an iterable of numbersfrom zero to the given numberprints:0123"""for i in range(4):print(i)复制代码如果我们传入两个参数,则代表迭代区间的首尾 。
""""range(lower, upper)" returns an iterable of numbersfrom the lower number to the upper numberprints:4567"""for i in range(4, 8):print(i)复制代码如果我们传入第三个元素,表示每次循环变量自增的步长 。


推荐阅读