List comprehension, dictionary comprehension, collection comprehension

1. List comprehension 

#coding:utf8
x1 = [x for x in range (5)]
print(x1)
odd = [x for x in range(10) if x % 2 !=0]
print(odd)

The results of the operation are: 

2. Dictionary comprehension

#coding:utf8
x1 = {n: n**2 for n in range(5)}
print(x1)
x2 = {v: k for k, v in x1.items()}
print (x2)

3. Set comprehension

Set comprehensions will help us remove duplicate elements

#coding:utf8
x1 = {i**2 for i in [-1,-5,1,2,-2]}
print(x1)

operation result:

Guess you like

Origin blog.csdn.net/wzhrsh/article/details/106575479