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


# Note that a tuple of length one has to have a comma after the last element but# tuples of other lengths, even zero, do not.type((1))# => <class 'int'>type((1,))# => <class 'tuple'>type(())# => <class 'tuple'>复制代码tuple支持list当中绝大部分操作:
# You can do most of the list operations on tuples toolen(tup)# => 3tup + (4, 5, 6)# => (1, 2, 3, 4, 5, 6)tup[:2]# => (1, 2)2 in tup# => True复制代码我们可以用多个变量来解压一个tuple:
# You can unpack tuples (or lists) into variablesa, b, c = (1, 2, 3)# a is now 1, b is now 2 and c is now 3# You can also do extended unpackinga, *b, c = (1, 2, 3, 4)# a is now 1, b is now [2, 3] and c is now 4# Tuples are created by default if you leave out the parenthesesd, e, f = 4, 5, 6# tuple 4, 5, 6 is unpacked into variables d, e and f# respectively such that d = 4, e = 5 and f = 6# Now look how easy it is to swap two valuese, d = d, e# d is now 5 and e is now 4复制代码解释一下这行代码:
a, *b, c = (1, 2, 3, 4)# a is now 1, b is now [2, 3] and c is now 4我们在b的前面加上了星号,表示这是一个list 。所以Python会在将其他变量对应上值的情况下,将剩下的元素都赋值给b 。
补充一点,tuple本身虽然是不可变的,但是tuple当中的可变元素是可以改变的 。比如我们有这样一个tuple:
a = (3, [4])复制代码我们虽然不能往a当中添加或者删除元素,但是a当中含有一个list,我们可以改变这个list类型的元素,这并不会触发tuple的异常:
a[1].append(0) # 这是合法的复制代码dictdict也是Python当中经常使用的容器,它等价于C++当中的map,即存储key和value的键值对 。我们用{}表示一个dict,用:分隔key和value 。
对 。我们用{}表示一个dict,用:分隔key和value 。
# Dictionaries store mappings from keys to valuesempty_dict = {}# Here is a prefilled dictionaryfilled_dict = {"one": 1, "two": 2, "three": 3}复制代码dict的key必须为不可变对象,所以list、set和dict不可以作为另一个dict的key,否则会抛出异常:
# Note keys for dictionaries have to be immutable types. This is to ensure that# the key can be converted to a constant hash value for quick look-ups.# Immutable types include ints, floats, strings, tuples.invalid_dict = {[1,2,3]: "123"}# => Raises a TypeError: unhashable type: 'list'valid_dict = {(1,2,3):[1,2,3]}# Values can be of any type, however.复制代码我们同样用[]查找dict当中的元素,我们传入key,获得value,等价于get方法 。
# Look up values with []filled_dict["one"]# => 1filled_dict.get('one') #=> 1复制代码我们可以call dict当中的keys和values方法,获取dict当中的所有key和value的集合,会得到一个list 。在Python3.7以下版本当中,返回的结果的顺序可能和插入顺序不同,在Python3.7及以上版本中,Python会保证返回的顺序和插入顺序一致:
# Get all keys as an iterable with "keys()". We need to wrap the call in list()# to turn it into a list. We'll talk about those later.Note - for Python# versions <3.7, dictionary key ordering is not guaranteed. Your results might# not match the example below exactly. However, as of Python 3.7, dictionary# items maintain the order at which they are inserted into the dictionary.list(filled_dict.keys())# => ["three", "two", "one"] in Python <3.7list(filled_dict.keys())# => ["one", "two", "three"] in Python 3.7+# Get all values as an iterable with "values()". Once again we need to wrap it# in list() to get it out of the iterable. Note - Same as above regarding key# ordering.list(filled_dict.values())# => [3, 2, 1]in Python <3.7list(filled_dict.values())# => [1, 2, 3] in Python 3.7+复制代码我们也可以用in判断一个key是否在dict当中,注意只能判断key 。
# Check for existence of keys in a dictionary with "in""one" in filled_dict# => True1 in filled_dict# => False复制代码如果使用[]查找不存在的key,会引发KeyError的异常 。如果使用get方法则不会引起异常,只会得到一个None:
# Looking up a non-existing key is a KeyErrorfilled_dict["four"]# KeyError# Use "get()" method to avoid the KeyErrorfilled_dict.get("one")# => 1filled_dict.get("four")# => None# The get method supports a default argument when the value is missingfilled_dict.get("one", 4)# => 1filled_dict.get("four", 4)# => 4setdefault方法可以为不存在的key插入一个value,如果key已经存在,则不会覆盖它:


推荐阅读