Python list comprehension, a collection of derivation, dictionary comprehensions

Python has a special expression is derivation, including a list comprehensions, set of derivation, dictionary comprehensions. By entering a sequence, usually for a cycle, together with the filter condition, generates a new sequence. A typical structure as shown below:
Here Insert Picture Description
Output Results:
Here Insert Picture Description
As can be seen all the even less than 10 square generates a new list, of course, we can also be filtered through a plurality of conditions, two formats are as follows:

n_list = [x ** 2 for x in range(100) if x % 2 == 0 if x % 5 ==0]
n_list1 = [x ** 2 for x in range(100) if x % 2 == 0 and x % 5 ==0]
print(n_list)
print(n_list1)

Here Insert Picture Description
The above list is actually equivalent to the following formula derived code:

n_list = []
for x in range(100):
    if x % 2 == 0 and x % 5 == 0:
        n_list.append(x**2)
print(n_list)

Here Insert Picture Description
Three forms of output are the same.


For the set of derivation, its form and usage and list comprehensions are basically the same, only need to be changed braces brackets can

n_list1 = {x ** 2 for x in range(100) if x % 2 == 0 and x % 5 ==0}
print(n_list1)

Here Insert Picture Description
List became a collection note here is that no set of repeating elements but the list can be repetitive elements, so in the final set of derivation formula will be repeated elements discarded. Similarly, the above code is equivalent to:

n_list = set()
for x in range(100):
    if x % 2 == 0 and x % 5 == 0:
        n_list.add(x**2)
print(n_list)

Here Insert Picture Description


Most notable is the derivation of usage dictionary, a dictionary because there are two elements corresponding to key and key storage, is slightly more complicated.

n_dic = {1:'one',2:'two',3:'three'}
print(n_dic)
out_dic = {k:v for k,v in n_dic.items() if k<3}
print(out_dic)

We have said before, to a value in the sequence, but the dictionary is not a sequence of items need to call the method is converted into a sequence.
Here Insert Picture Description
Dictionary There are other more flexible to use, you can just take the key or keys, such as:

n_dic = {1:'one',2:'two',3:'three'}
print(n_dic)
out_dic = {k for k,v in n_dic.items() if k<3}
print(out_dic)

Here Insert Picture Description
In this case the use of braces becomes a set of derivation, in square brackets is a list of comprehension.

Published 58 original articles · won praise 69 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_43157190/article/details/104772677