from random import randint,sample # random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。 s1 = {x: randint(3,4) for x in sample('abcdef',randint(4,6))} s2 = {x: randint(3,4) for x in sample('abcdef',randint(4,6))} s3 = {x: randint(3,4) for x in sample('abcdef',randint(4,6))} print(s1) print(s2) print(s3)
''' This PEP proposes to change the .keys(), .values() and .items() methods of the built-in dict type to return a set-like or unordered container object whose contents are derived from the underlying dictionary rather than a list which is a copy of the keys, etc ''' # 其中.keys().items() 返回的是一个set-like 对象,所以set具备的集合计算也可以用 help(dict.keys) help(dict.values) help(dict.items)
from functools import reduce print(reduce(lambda a,b:a&b,r)) # 前面如果有print把r1这个 Iterator 序列全部打出来,r1里面就是空的,所以这里如果用r1就会报错
print(list(r1)) #空序列,因为前面print完了
print(reduce(lambda a,b:a&b,r1))
[dict_keys(['d', 'a', 'e', 'f']), dict_keys(['c', 'b', 'e', 'f']), dict_keys(['e', 'c', 'd', 'a'])]
{'e'}
[]
[]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-73-b7dcf2afc47f> in <module>()
32 print(list(r1)) #空序列,因为前面print完了
33
---> 34 print(reduce(lambda a,b:a&b,r1))
35
36
TypeError: reduce() of empty sequence with no initial value
函数与方法的区别
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#函数与方法的区别 ''' 在Python中,对这两个东西有明确的规定: 函数function —— A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body. 方法method —— A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). 与类和实例无绑定关系的function都属于函数(function); 与类和实例有绑定关系的function都属于方法(method)。 ''' #函数与方法 ??? s1.keys() == dict.keys(s1) #(方法)s1.keys() == dict.keys(s1)(函数)???'