Python list comprehension, generator expressions, dictionary derivation, derivation using collections
推导式是可以从一个数据序列构建另一个新的数据序列的结构体
First, list comprehensions:
Use []
parentheses generate a list
General operation:
# 需求:将my_list列表中的奇数取出, 并且将取出的奇数相乘, 并且返回
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
new_list = []
for item in my_list:
if item % 2 == 1:
new_list.append(item*item)
print(new_list)
# 输出结果如下:[1, 9, 25, 49]
Operation list derived using the formula:
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
new_list = [item * item for item in my_list if item % 2 == 1]
print(new_list)
# 输出结果:[1, 9, 25, 49]
Second, the generator expression:
Use ()
parentheses generator into the derivation of formula list []
changed ()
can be obtained Builder
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
new_genertor = (item for item in my_list if item % 2 == 1)
print(new_genertor) # 输出结果:<generator object <genexpr> at 0x0000027752962200>
# 循环生成器
for item in new_genertor:
print(item)
# 输出结果如下:
1
3
5
7
Third, dictionary comprehensions:
Use {}
brackets and the list is stored 键值对
, it is a dictionary comprehension
my_dict = {"name": "fe_cow", "age": 22, "sex": "男"}
new_dict = {value: key for key, value in my_dict.items()}
print(type(new_dict))
# 输出结果:<class 'dict'> 可以看出是一个字典
print(new_dict)
# 输出结果:{'fe_cow': 'name', '男': 'sex', 22: 'age'} 仅是将字典中的键值掉换了位置
Fourth, the set of derivation:
Use the same set of derivation is {}
bracketed to indicate, with the only difference is that the dictionary derivation, it inside不是键值对
my_dict = {"name": "fe_cow", "age": 22, "sex": "男"}
new_set = {key for key, value in my_dict.items()}
print(type(new_set))
# 输出结果:<class 'set'> 可以看出它是一个集合类型
print(new_set)
# 输出结果:{'sex', 'name', 'age'}
These are some simple derivation use is not recommended to use more complex logic for processing derivations, 因为代码的可读性是很重要的
.