In this question, we expect to get the result of finding out who is the player who has scored each round in the rounds. Let's use Python to simulate this, Sir, into a batch of data:
>>> fromRandomImportrandint, sample>>>#Sample is the meaning of sampling, such as sample (' ABCDE ', 2), which will randomly sample 2 characters in the ' ABCDE ' string.>>> {x:randint (1,3) forXinchSample'abcdef', Randint (3, 6))}{'a': 2,'b': 2,'e': 2,'D': 3,'F': 2}>>>#use the above method to generate data for 3 rounds of competition>>> S1 = {X:randint (1,3) forXinchSample'abcdef', Randint (3, 6))}>>> s2 = {X:randint (1,3) forXinchSample'abcdef', Randint (3, 6))}>>> s3 = {X:randint (1,3) forXinchSample'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 data, and want to get a round of rounds, which player scored in each game, there are several ways:
One. Traversal
>>> res = [] for in S1:>>> ifin and in S3:>>> res.append ()>>> res[' a ' ' b ' ' F ']
This method is inefficient and cumbersome
Two. and arithmetic
>>>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'])
And the operation is clear, the elements of the set set are not repeated by the nature.
Three. Map and reduce
In fact, we use and operation has been more convenient to get the public key, but this problem has an extension, if more than 3 rounds? If there are many or unknown wheels (S1,S2,S3...SN), then the map and reduce functions need to be introduced.
Here is a brief introduction to only two functions, not entirely.
The map (f, list) function accepts two necessary parameters, the function f and the list, and returns a list in which all the elements in the list are the result of the calculation of all elements in the parameter list according to function F. 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 map, whose argument f function receives two parameters, and all elements in the returned list are the result of the cumulative calculation of all elements in the parameter list according to function f, such as additive/multiplicative:
>>> L = [1,2,3,4,5]>>> reduce (lambda x,y:x+y, l)15>>> reduce ( Lambda x,y:x*y, l)120
Then using these two functions, in conjunction and operation, can solve this problem perfectly:
>>>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 (Lambdax,y:x&y, Map (Dict.viewkeys, [S1, S2, S3]) set (['a','b','F'])
Python Intensive Training Note (v)--find common keys in multiple dictionaries