Python list comprehension generator expression

List comprehension

# 列表推导式就是使用一个简单的方法创建一个列表
# 列表里元素的类型是根据for前面的数据类型而定的
a = [m for m in range(31)]
print(a)# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

b = [a[m:m + 3] for m in range(0, 31, 3)]# 这里的a就是上面定义的a列表
print(b)# [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29], [30]]

c = [(a, b) for a in range(0, 2) for b in range(3, 5)]
print(c)# [(0, 3), (0, 4), (1, 3), (1, 4)]

i = [[1, 4, 7],
     [2, 5, 8],
     [3, 6, 9]]
d = [row[1] for row in i]
print(d) # [4, 5, 6]

e = [i[j][j] for j in range(len(i))]
print(e) # [1, 5, 9]

f = [i[j][2-j] for j in range(len(i))]
print(f)# [7, 5, 3]

After the loop, you can also follow the judgment, so that you can perform simple data filtering.
Look at the following demonstration:

num3 = [1,-1,2,-2,-10,3,4]
print([x for x in num3 if x > 0])# [1, 2, 3, 4]

Find the sum of even numbers within 100, find all the numbers within 100 that are divisible by 3 and whose ones place is 2, and there are many of the same types, which can also be obtained in this way:
(Although this can also be obtained by modifying the step It's long, but I still need to talk about it)

num1 = [x for x in range(101) if x % 2 == 0]# 这里我就不去打印了
print(sum(num1))# 2550
print([i for i in range(101) if i % 3 == 0 and  i % 10 == 2])# [12, 42, 72]

You can also perform operations on the values ​​in the list, such as exponentiation

print([i ** 2 for i in range(5)])# [0, 1, 4, 9, 16]

Find all the factors of a number. This can be helpful for judging whether a number is complete. Just replace n+1 with n, and then compare in the sum
(the so-called complete number means that the number is exactly equal to divide itself The sum of external factors. For example: 6=1+2+3)

n = 6
print([i for i in range(1,n+1) if n % i == 0])# [1, 2, 3, 6]

analogy

There are list comprehensions, but are there tuples, dictionaries, and set comprehensions? This is what we should think about.
Let’s try it now. It’s nothing more than changing the packaging.

num = (i for i in range(5))
print(num) # <generator object <genexpr> at 0x09AEEE30>
print(type(num))# <class 'generator'>
# 显然好像不是元组
# 这是一个生成器对象
# 我们可以对他进行遍历,也可以使用next()方法去调用它
# 但是这样生成器只能使用一次,也不能说是使用一次吧,
# 就是当生成器里的数据被迭代完时,里面的数据就为空了
# 看下面的演示
for i in num :
    print(i)
# 0
# 1
# 2
# 3
# 4
print(list(num))# []

# print(next(num))# 0
# print(next(num))# 1
# print(next(num))# 2
# print(next(num))# 3
# print(next(num))# 4
# print(list(num))# []

Wrapped in () is actually a generator expression. In Python, a function that uses yield is called a generator. Unlike ordinary functions, a generator is a function that returns an iterator and can only be used for iteration Operation, it’s easier to understand that a generator is an iterator

# 定义一个返回前n个斐波那契数列生成器函数
def feibo(n):
    a,b = 0,1
    for i in range(n):
        a,b = b ,a+b
        yield a
print(feibo(10))# <generator object feibo at 0x09DDEEB0>
print(list(feibo(10)))# [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

When the generator expression is passed as a separate parameter to the function, the outer de() can be omitted.
Using a generator expression as a parameter is more efficient than creating a temporary list first.

s1 = sum((x for x in range(101))) # 显示的传递一个生成器表达式对象
s2 = sum(x for x in range(101)) # 更加优雅的实现方式,省略了括号
print(s1)# 5050
print(s2)# 5050
# min()、max()函数也是同理
person = [
    {
    
    'name':'zhangsan','age':20},
    {
    
    'name':'lisi','age':18},
    {
    
    'name':'wangwu','age':16},
    {
    
    'name':'maliu','age':17},
]
print(min(p['age'] for p in person))# 16
print(min(person,key=lambda p:p['age']))# {'name': 'wangwu', 'age': 16}



Let's look at {}
a = {
    
    x for x in range(10)}
print(a)# {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
print(type(a))# <class 'set'>

student = {
    
    
    'name':'zhangsan','age':18
}
b = {
    
    x:y for y,x in student.items()}
print(b)# {'zhangsan': 'name', 18: 'age'}
print(type(b))# <class 'dict'>

It feels useless, just reversing the dictionary is still useful

What needs to be mastered is the list comprehension and generator expression


La la la
It's time for everyone to like it again
You can also triple O with one click
QAQ

Guess you like

Origin blog.csdn.net/hmh4640219/article/details/112600511