There is not that a question, so that you really understand from the Python programming?

Write down the title when the mind can not suppress the kin that sounded slightly hoarse voice:

The distance came that familiar song,
why did those voices weak.
Long time no see, you all right now?
There are not that a song
makes you gently along and,
with the ups and downs of our lives,
sing the theme song together;
there is not that a song
makes you suddenly think of me,
make you happy but also makes you worry,
so I have a ......

End musical, back to the topic. Recently browse LeetCode, found a very interesting little title. When I try to answer in Python, when actually spent a collection, map functions, zip function, lambda functions, sorted function, the debugging process also involves the iterators, generators, list comprehensions concept. A seemingly very simple subject, although the final code can be combined into one line, but almost the Python programming techniques used again, described as "see the spirit of nuances"! With this title, it may make you really understand from the Python programming.

This question is called "lucky number in the list." What is it lucky number? In the list of integers, if there is frequency and its value is equal to the size of a number, we call this number as "lucky number." For example, the list [1, 2, 2, 3], the number of figures 1 and Number 2 are 1 and 2 respectively, they are lucky number, but there have been a 3, 3 is not a lucky number.

Understand the concept of lucky numbers, we have to try to find a list [3, 5, 2, 7, 3, 1, 2, 4, 8, 9, 3] in it lucky number. This process can be divided into the following steps:

  1. The list does not identify duplicate numbers
  2. Count the number of times each number appears in the list
  3. The number of times equal to those numbers appear to find the numbers themselves

Step 1, the list does not identify duplicate numbers

The list does not identify duplicate numbers, that is, to remove the list of repeating elements, referred to as the "go heavy." Deduplication most simple way is to use the collection.

>>> arr = [3,5,2,7,3,8,1,2,4,8,9,3]
>>> unique = set(arr)
>>> unique
{1, 2, 3, 4, 5, 7, 8, 9}

Step number 2, statistics for each number appears in the list

We know that the list of objects comes a count () method returns the number of an element can appear in the list are used as follows:

>>> arr = [3,5,2,7,3,8,1,2,4,8,9,3]
>>> arr.count(8) # 元素8在数组arr中出现过2次
2

Next, we need only to traverse each element of de-duplicated, one by one to count the number of their respective appear, and save it as an appropriate data structure, which further work is needed.

>>> arr = [3,5,2,7,3,8,1,2,4,8,9,3]
>>> unique = set(arr) # 去除重复元素
>>> pairs = list() # 空列表,用于保存数组元素和出现次数组成的元组
>>> for i in unique:
		pairs.append((i, arr.count(i)))
	
>>> pairs
[(1, 1), (2, 2), (3, 3), (4, 1), (5, 1), (7, 1), (8, 2), (9, 1)]

As a novice, this code is written, it has been very good. However, there is a pursuit of the programmer will never complacent, stagnant. Their favorite thing to do is try to do everything possible to destroy the for loop, such as using the mapping function, filter function to replace the for loop; if not refuse for recycling, they will hide as much as possible to cycle, such as hidden in the list comprehensions. Here since it is to count a list of every element calls () this method, it is the most suitable substitute for circulating a map function.

>>> m = map(arr.count, unique)
>>> m
<map object at 0x0000020A2D090E08>
>>> list(m) # 生成器可以转成列表
[1, 2, 3, 1, 1, 1, 2, 1]
>>> list(m) # 生成器只能用一次,用过之后,就自动清理了
[]

map function returns a generator (generator), can traverse the same as the list, but not as visually see the various elements like lists, unless we use list () to turn the generator to the list (you do not actually need to generator into a list). Note that different generators and iterators, or Builder is a special kind of iterator, can only be traversed once, traversing the end, it automatically disappears. Iterator can be repeatedly traversed. For example, range () function returns iterators:

>>> a = range(5)
>>> list(a)
[0, 1, 2, 3, 4]
>>> list(a)
[0, 1, 2, 3, 4]

Having generators and iterators, we have to return to the original topic. Use map mapping function, we obtain the number of occurrences of each element, and also needs a corresponding element consisting of a tuple. This time, they were using zip () function of. zip () function to create a builder for the polymerization may each iteration object (iterators, generators, list, tuple, set, string, etc.) of the element, the element polymerized in the same subscript, is ignored different lengths greater than iteration object element shortest length.

>>> m = map(arr.count, unique)
>>> z = zip(unique, m)
>>> z
<zip object at 0x0000020A2D490508>
>>> list(z)
[(1, 1), (2, 2), (3, 3), (4, 1), (5, 1), (7, 1), (8, 2), (9, 1)]
>>> list(z)
[]

Obviously, zip () function returns also the generator can only be used once, and after that is gone.

Step 3, the numbers of times equal to the number itself appears to find

With its number of occurrences of each element, we just need to loop through ...... no, wait, why do we have to cycle it? We just take each element filter again, identify those elements themselves equal to the number of occurrences of those tuples, why not try the filter function filter () do?

>>> def func(x): # 参数x是元组类型
		if x[0] == x[1]:
			return x
	
>>> m = map(arr.count, unique)
>>> z = zip(unique, m)
>>> f = filter(func, z)
>>> f
<filter object at 0x0000020A2D1DD908>
>>> list(f)
[(1, 1), (2, 2), (3, 3)]
>>> list(f)
[]

Filter function filter () accepts two parameters, the first parameter is a function for determining whether an element matching the filter, the second parameter is the need to filter the objects may be iterative. filter () function is the return of the generator, can only be used once, i.e., after the disappearance.

Write here, we almost done. However, as a pursuit of a programmer, you can tolerate func () looks strange such a function? The answer is no! You will replace it with a lambda functions. In addition, we may also need to sort the results according to the size of the element. Plus sorting, complete code is as follows:

>>> arr = [3,5,2,7,3,8,1,2,4,8,9,3]
>>> unique = set(arr)
>>> m = map(arr.count, unique)
>>> z = zip(unique, m)
>>> f = filter(lambda x:x[0]==x[1], z)
>>> s = sorted(f, key=lambda x:x[0])
>>> print('幸运数是:', [item[0] for item in s])
幸运数是: [1, 2, 3]

The ultimate code, a line to get

If you've ever been written that line, was able to implement complex functions, the code looks like hieroglyphics like the ravages of bitter experience, then, now you can put the above code into a single line, to the ravages of someone else.

>>> arr = [3,5,2,7,3,8,1,2,4,8,9,3]
>>> print('幸运数是:', [item[0] for item in sorted(filter(lambda x:x[0]==x[1], zip(set(arr), map(arr.count, set(arr)))), key=lambda x:x[0])])
幸运数是: [1, 2, 3]
Published 101 original articles · won praise 10000 + · views 1.56 million +

Guess you like

Origin blog.csdn.net/xufive/article/details/105215593