Getting started N day
Comprehension: expressions used to quickly and easily generate lists or dictionaries
-
List comprehension
-
basic structure
List=[expression for variable in sequence]
Generate a new list, the elements in the list are the result of the expression corresponding to each loop
Is equivalent to:
List=[]
for variable in sequence:
List.append(expression)
list1 = [10 for i in range(3)] print(list1) # [10, 10, 10] list2 = [2 * i for i in range(1, 4)] print(list2) # [2, 4, 6]
Exercise: Write a list comprehension to produce a list of elements that satisfy the following rules: str0,str3,str6,...,str99
list3=[f'str{i}'for i in range(0,100,3)] print(list3)
-
Conditional structure
List=[expression for variable in sequence if conditional statement]
Is equivalent to:
List=[]
for variable in sequence:
if conditional statement:
List.append (expression)
Exercise: Write a list comprehension to produce a list of elements that satisfy the following rules: str1,str3,str6,...,str99
method one
list1=[f'str{i}' for i in range(1,100) if i % 3 == 0 or i == 1 ] print(list1)
Method 2: ternary operator
list2=['str1' if i == 0 else f'str{i}' for i in range(0,100,3)] print(list2)
-
Multiple loop structure 1:
List=[expression for variable 1 in sequence 1 for variable 2 in sequence 2]
Is equivalent to:
List=[]
for variable 1 in sequence 1:
for variable 2 in sequence 2:
List.append(expression)
-
Multiple loop structure 2:
List=[expression for variable 1 in sequence 1 if conditional statement for variable 2 in sequence 2 If conditional statement]
Is equivalent to:
List=[]
for variable 1 in sequence 1:
if conditional statement:
for variable 2 in sequence 2:
if conditional statement:
List.append(expression)
-
# 集合推导式 a1 = { i for i in 'hello'} print(a1) # {'h', 'e', 'l', 'o'} # 元组和集合推导式 a2 = tuple(x * 2 for x in 'hello') print(a2) # ('hh', 'ee', 'll', 'll', 'oo') # 字典推导式 a3 = { x: x * 2 for x in 'hello'} print(a3) # {'h': 'hh', 'e': 'ee', 'l': 'll', 'o': 'oo'} a4 = dict((x, x * 2) for x in 'hello') print(a4) # {'h': 'hh', 'e': 'ee', 'l': 'll', 'o': 'oo'} # 练习3 通过字典推导式交换一个字典的键和值 dic={'a':10,'b':20,'c':30} dic1 = { 'a': 10, 'b': 20, 'c': 30} # dic12 = dict((dic1[i], i) for i in dic1) dic2 = { dic1[i]: i for i in dic1} print(dic2) # 通过字典推导式交换一个字典的键和值 如果值是可变的在新的字典中不交换 dic3 = { 'a': 10, 'b': 20, 'c': 30, 'd': [10, 20]} dic4 = dict((i,dic3[i]) if type(dic3[i]) in (list,set,dict) else (dic3[i],i) for i in dic3) print(dic4)