Python list comprehension, tuple comprehension dictionary comprehension, ternary operator

1. Basic grammatical structure

The basic grammatical structure of a list comprehension is:

[ expression for item in iterable if condition ]

Among them, expression represents the expression that participates in the generation of the list, which can include operations such as variables and function calls ; item represents the elements in the generated list; iterable represents iterable objects, such as lists, tuples, sets, etc.; if condition represents the condition filter, can be omitted.

expression represents the expression to operate on each item, item is each element in the iterable object, and if condition is an optional filter condition. After the execution is complete, a new list new_list will be obtained.


"""
生成1-9的整数列表
"""
myList =  [x for x in range(1,10)]
#  [1,2,3,4,5,6,7,8,9]
print(myList)



"""
生成1~9之间的整数的平方列表
"""
square_list = [i**2 for i in range(1,11)]
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
print(square_list)


"""
从一个字符串列表中筛选出长度超过3的字符串
"""

str_list = ['hello', 'world', 'python', 'list', 'comprehension', 'study']

new_list = [s for s in str_list if len(s) > 3]
# 
print(new_list)


multiple loops


my_list = [n*m for n in range(1,3) for m in range(1,3) ]
# 此处通过两层循环实现了乘法操作,即n和m分别取1、2时,它们的乘积构成了列表中的元素
# [1,2,2,4]
print(my_list)

nested list comprehension

insert image description here

Sometimes it is necessary to perform more complex operations on the elements when generating a list. In this case, nested list comprehensions can be used. Nested list comprehension means to nest list comprehension formula again on the basis of list comprehension formula, its grammatical structure is:

[ expression for item in iterable if condition for sub_item in sub_iterable if sub_condition ]

Among them, the meanings of expression, item, iterable and condition are consistent with the above-mentioned basic grammatical structure; sub_item indicates the element traversed again on the basis of item traversal ; sub_iterable indicates the iteration object of sub_item; sub_condition indicates the filter condition for sub_item.


matrix = [[i*j for j in range(1,4)] for i in range(1,4)]
for row in matrix:
    print(row)

"""
[1, 2, 3]

[2, 4, 6]

[3, 6, 9]
"""


my_list = [
    [[1, 2, 3], [4, 5, 6]]
]
flat = [x for sub1 in my_list for sub2 in sub1 for x in sub2]
print(flat)
# [1, 2, 3, 4, 5, 6]
 
flat2 = [((x for x in sub2) for sub2 in sub1) for sub1 in my_list]
print(list(flat))
# [1, 2, 3, 4, 5, 6]

tuple comprehension

A tuple comprehension is similar to a list comprehension, except that the square brackets are replaced by parentheses.
The tuple comprehension is different from the list comprehension. It generates an object, a generator object, not a tuple directly; if you want to get a tuple or list, you need to pass tuple() or list() to convert.

import random
randomnumber = (random.randint(10, 100) for i in range(10))
print(randomnumber)
>>>
<generator object <genexpr> at 0x00000165F97CE5C8>
我们发现并没有生成元组,而只是得到了一个生成器,我们还需要转换一下:

import random
randomnumber = (random.randint(10, 100) for i in range(10))
print(tuple(randomnumber))
>>>
(68, 39, 49, 22, 34, 39, 12, 53, 19, 29)
综上,我们使用元组推导式时,得到的并不是一个元组,而是一个生成器,如果我们希望输出元组,我们还需要使用tuple() 函数转换一下。

另外,我们还可以直接遍历生成器:

import random
randomnumber = (random.randint(10, 100) for i in range(10))
##print(tuple(randomnumber))
for i in randomnumber:print(i, end = " ")
>>>
75 88 76 77 65 13 82 31 71 35 


import random
print(tuple(random.randint(10,1000) for i in range(10)))
print(list(random.randint(10,1000) for i in range(10)))
 
输出为:
(930, 139, 668, 598, 493, 936, 742, 763, 339, 205)
[437, 689, 372, 171, 876, 451, 336, 903, 513, 727]  

The result of a tuple comprehension is a generator object, not a tuple.

If we don't want to convert to a tuple or list , but still want to output the contents of the generator, we need to use a for loop to traverse it.

import random
yz=(random.randint(10,1000) for i in range(10))
for i in yz:
	# 输出的是单个数,并不是元组;如果用默认的换行的话,输出的数更是每个一行(所以输出没有外面的括号);
    print(i,end=' ') #不换行,用空格分割
 
输出为:
 
725 10 513 74 42 683 143 997 315 795 

magic method

For the generator object, in addition to using the for loop to traverse it, you can also use __next__ to traverse it

import random #导入随机数模块
yz=(random.randint(10,1000) for i in range(10))
print(yz.__next__())#输出生成器中的第一个元素
print(yz.__next__())#输出生成器中的第二个元素
print(yz.__next__())#输出生成器中的第三个元素
 
420
709
760

It can be seen that when the for loop outputs 10 elements in the generator object; it is converted into a tuple output again, but the content of the generator is empty at this time, because: when
we access the content of the generator object, The generator object no longer exists,
so after converting it, it is an empty tuple;

If you want to use this generator object again, you must regenerate it.

import random #导入随机数模块
yz=(random.randint(10,1000) for i in range(10))
for i in yz:
    print(i,end=' ')
print(tuple(yz))
 
输出为:
935 51 628 73 392 442 145 694 369 173 ()

dictionary comprehension

Grammar 1

new_dictionary = {key_exp:value_exp for key, value in dict.items() if condition}
字典推导式说明:
key:dict.items()字典中的key
value:dict.items()字典中的value
dict.items():序列
condition:if条件表达式   :  可以用key,也可以用value   
key_exp:在for循环中,如果if条件表达式condition成立(即条件表达式成立),返回对应的**key,value当作key_exp,value_exp**处理 
value_exp:在for循环中,如果if条件表达式condition成立(即条件表达式成立),返回对应的**key,value当作key_exp,value_exp**处理
这样就返回一个新的字典。
    dictionary_1 = {
    
    'a': '1234', 'B': 'FFFF', 'c': ' 23432', 'D': '124fgr', 'e': 'eeeee', 'F': 'QQQQQ'}

    # 案例一:获取字典中key值是小写字母的键值对
    new_dict_1 = {
    
    key: value for key, value in dictionary_1.items() if key.islower()}
    new_dict_2 = {
    
    g: h for g, h in dictionary_1.items() if g.islower()}
    # g, h只是一个变量,使用任意字母都行,但是一定要前后保持一致。
    print(new_dict_1)
    print(new_dict_2)

	
	# 案例二:将字典中的所有key设置为小写
	#  字典推导式 key:可以是变量,也可以是表达式,函数等
	new_dict_3 = {
    
    key.lower(): value for key, value in dictionary_1.items()}
	# 将字典中的所有key设置为小写,value值设置为大写
	new_dict_4 = {
    
    key.lower(): value.upper() for key, value in dictionary_1.items()}
	print(new_dict_3)
	print(new_dict_4)

The ternary expression, also known as the ternary operator , is a fixed format in software programming, and the syntax is "conditional expression? expression 1: expression 2". Often used to assign values ​​to variables based on conditions.
There are also ternary expressions in Python, but the ternary operator of Python is different from languages ​​such as C and Java. The grammatical format is:
expression 1 if conditional expression else expression 2
When the expression returns True, return the result expression1, otherwise return the result expression2

Syntax 2
{key_exp:value_exp1 if condition else value_exp2 for key, value in dict.items()}
Dictionary derivation description:
key: key in dict.items() dictionary
value: value dict in dict.items() dictionary
. items(): sequence
condition: the judgment content of the if conditional expression
value_exp1: in the for loop, if the conditional expression condition is established (that is, the conditional expression is established), return the corresponding key, value and make key_exp, value_exp1 process
value_exp2: in In the for loop, if the conditional expression condition is not true (that is, the conditional expression is not true), return the corresponding key, value and do key_exp, value_exp2 processing

insert image description here

# 在爬虫中,我们需要获取cookies并以字典的形式传参,如果cookies是字符串则需要转换为字典,经典代码案例如下:
# 原来的cookies很长,这里截取一部分做演示:
cookies = "anonymid=jy0ui55o-u6f6zd; depovince=GW; _r01_=1; JSESSIONID=abcMktGLRGjLtdhBk7OVw; ick_login=a9b557b8-8138-4e9d-8601-de7b2a633f80"
# 字典推导式,将长的字符串转化为字典。
new_dict_1 = {
    
    cookie.split("=")[0]: cookie.split("=")[1] for cookie in cookies.split(";")} 
print(new_dict_1)
"""
代码分析:
在字符串cookies中’=’前面是key,’=’后面是value,每一个’;’构成一个键值对;多个键值对构成一个字典;
1.根据’;’将字符串拆分为列表;
2.根据第一步获取的列表,遍历时将每一个字符串根据’=’再次拆分;
3.根据第二步拆分的结果,列表第一个元素作为key,列表第二个元素作为value;
"""
new_dict_2 = {
    
    key: value for t in cookies.split(";") for key, value in (t.split("="),)}
# 先将字符串通过';'分解成短的带有等号的字符串,然后将这个短的字符串转化为元组,最后再通过'='分解成俩个值分别赋给key、value。
print(new_dict_2)
"""
# 下面是分解的演示:
for t in cookies.split(';'):
    print(type(t))
    print((t.split('='),))
    print(type((t.split('='),)))
print(cookies.split(';'))
"""

insert image description here

The ternary expression, also known as the ternary operator, is a fixed format in software programming, and the syntax is "conditional expression? expression 1: expression 2". Often used to assign values ​​to variables based on conditions.
There are also ternary expressions in Python, but Python's ternary operator is different from languages ​​such as C and Java. The syntax format is:

Expression 1 if conditional expression else Expression 2
When the expression returns True, return the result expression 1, otherwise return the result expression 2

Affirmation

assert expression [, arguments]
insert image description here

result = assert a, b is similar to C# ??

insert image description here

Guess you like

Origin blog.csdn.net/u013400314/article/details/131547954
Recommended