Python intensive training notes (5)-find the public keys in multiple dictionaries and perform intensive training in python
In this case, we expected to find out who scored in each round in the three rounds. The following uses python to simulate a batch of data:
>>> From random import randint, sample >>># sample indicates sampling, for example, sample ('abcde', 2 ), the string 'abcde' will randomly sample 2 Characters >>> {x: randint () for x in sample ('abcdef ', randint (3, 6)} {'A': 2, 'B': 2, 'E': 2, 'D': 3, 'F ': 2 }>>># use the above method to generate data for three rounds of competition >>> s1 = {x: randint () for x in sample ('abcdef ', randint (3, 6) >>>> s2 = {x: randint (1, 3) for x in sample ('abcdef', randint (3, 6) >>> s3 = {x: randint (1, 3) for x in sample ('abcdef', randint (3, 6) >>># observe s1, s2, s3 >>> s1 {'A': 2, 'B': 4, 'F': 1 }>>> s2 {'A': 4, 'B ': 3, 'E': 2, 'D': 4, 'G': 3, 'F': 4 }>>> s3 {'A': 3, 'B': 4, 'E': 2, 'D': 2, 'F': 1}
As shown in the code above, we have generated three rounds of competition data. To get three rounds of competition, which player scored in each round, there are several methods:
1. Traverse
>>> res = []>>> for x in s1:>>> if x in s2 and x in s3:>>> res.append()>>> res['a', 'b', 'f']
This method is inefficient and cumbersome
Ii. Operation
>>> s1.viewkeys()dict_keys(['a', 'b', 'f'])>>> s2.viewkeys()dict_keys(['a', 'b', 'e', 'd', 'g', 'f'])>>> s3.viewkeys()dict_keys(['a', 'b', 'e', 'd', 'f'])>>> s1.viewkeys() & s2.viewkeys() & s3.viewkeys()set(['a', 'b', 'f'])
The operation is clear and clear, and the elements of the set are not repeated.
3. map and reduce
In fact, we can easily obtain the Public Key through the use and operation, but there is an extension to this problem. What if there are more than three rounds? If there are many or many unknown wheels (s1, s2, s3... sn), we need to introduce map and reduce functions.
Here we will only briefly introduce the two functions, not completely.
The map (f, list) function accepts two necessary parameters: function f and list. A list is returned, all the elements in the list are calculated based on function f in the parameter list. For example:
>>> l = [1,2,3,4,5]>>> map(lambda x: x*x, l)[1,4,9,16,25]
The reduce (f, list) function is similar to the map function. Its Parameter f function receives two parameters, all the elements in the returned list are the results of the cumulative calculation of all elements in the parameter list according to function f, such as accumulate/accumulate:
>>> l = [1,2,3,4,5]>>> reduce(lambda x,y: x+y, l)15>>> reduce(lambda x,y: x*y, l)120
Using these two functions, we can perfectly solve this problem through cooperation and computation:
>>> map(dict.viewkeys, [s1, s2, s3])[dict_keys(['a', 'b', 'f']), dict_keys(['a', 'b', 'e', 'd', 'g', 'f']), dict_keys(['a', 'b', 'e', 'd', 'f'])]>>> reduce(lambda x,y: x&y, map(dict.viewkeys, [s1, s2, s3]))set(['a', 'b', 'f'])