smaple 随机取样
In [9]: from random import randint,sample In [10]: sample('abcdefg',randint(3,6)) Out[10]: ['d', 'b', 'e', 'f', 'a', 'g'] In [11]: sample('abcdefg',randint(3,6)) Out[11]: ['b', 'd', 'a', 'c', 'f', 'g'] In [12]: sample('abcdefg',randint(3,6)) Out[12]: ['e', 'd', 'g', 'f', 'b', 'c'] In [13]: s1 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))} In [15]: s1 Out[15]: {'a': 2, 'b': 3, 'c': 2, 'e': 2, 'f': 3} In [16]: s2 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))} In [17]: s3 = {x:randint(1,4) for x in sample('abcdefg',randint(3,6))} In [18]: s3 Out[18]: {'a': 1, 'b': 1, 'c': 3, 'd': 1, 'e': 1, 'g': 2} In [19]: s2 Out[19]: {'a': 2, 'b': 2, 'c': 1, 'd': 1, 'f': 1}
In [25]: res = [] In [26]: for x in s1: ....: if x in s2 and x in s3: ....: res.append(x) ....: res ....: Out[26]: ['a', 'c', 'b'] In [142]: def inclues(seq1,seq2,seq3): res = [] for x in seq1: if x in seq2 and x in seq3: res.append(x) return res .....: In [143]: inclues(s1,s2,s3) Out[143]: ['e', 'f'] In [27]: s1 Out[27]: {'a': 2, 'b': 3, 'c': 2, 'e': 2, 'f': 3} In [28]: s2 Out[28]: {'a': 2, 'b': 2, 'c': 1, 'd': 1, 'f': 1} In [29]: s3 Out[29]: {'a': 1, 'b': 1, 'c': 3, 'd': 1, 'e': 1, 'g': 2} In [40]: [x for x in s1 if x in s2 and x in s3] Out[40]: ['e', 'f'] In [42]: list(filter(lambda x:x in s2 and x in s3,s1)) Out[42]: ['e', 'f']
In [37]: s1.viewkeys? Type: builtin_function_or_method String form: <built-in method viewkeys of dict object at 0xb614bacc> Docstring: D.viewkeys() -> a set-like object providing a view on D's keys
In [38]: s1.viewkeys() & s2.viewkeys() & s3.viewkeys() Out[38]: {'a', 'b', 'c'} 在N个字典的情况下: In [136]: reduce(lambda x,y: x & y,map(dict.viewkeys,[s1,s2,s3])) Out[136]: {'f', 'g'}
python2.x viewkeys()
python3.x直接用keys()
In [132]: s1.keys() & s2.keys() & s3.keys() Out[132]: {'f', 'g'} In [133]: map(dict.keys,[s1,s2,s3]) Out[133]: <map at 0xb5c9684c> In [134]: from functools import reduce
In [135]: reduce? Type: builtin_function_or_method String form: <built-in function reduce> Docstring: reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
在N个字典的情况下: In [136]: reduce(lambda x,y: x & y,map(dict.keys,[s1,s2,s3])) Out[136]: {'f', 'g'}