列表生成式
1. [x for x in data if condition]
此处if主要起条件判断作用,data数据中只有满足if条件的才会被留下,最终生成一个数据列表。
2. [exp1 if condition else exp2 for x in data]
此处if…else主要起赋值作用。当data中的数据满足if条件时,将其做exp1处理,否则按照exp2处理,最终生成一个数据列表。
一、
列表生成式即List Comprehensions,
是Python内置的非常简单却强大的可以用来创建list的生成式。
例如:
要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 可以用 range(1, 11)
二、
[x * x for x in range(1, 11)]
运行结果
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
三、
可以在后面加条件。
[x * x for x in range(1, 11) if x % 2 == 0]
运行结果
[4, 16, 36, 64, 100]
四、
可以放多重循环。
[m + n for m in 'ABC' for n in 'XYZ']
运行结果:
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
五、
结合字典使用
d = {'x': 'A', 'y': 'B', 'z': 'C' }
print([k + '=' + v for k, v in d.items()])
运行结果:
['x=A', 'y=B', 'z=C']
集合生成式
与列表生成式类似。
my_data = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (7, 8, 9)]
set_of_tuples1 = {x for x in my_data}
print("Output #2 (set comprehension): {}".format(set_of_tuples1))
set_of_tuples2 = set(my_data) # 内置的set函数更好
print("Output #3 (set function): {}".format(set_of_tuples2))
运行结果:
Output #2 (set comprehension): {(4, 5, 6), (7, 8, 9), (1, 2, 3)}
Output #3 (set function): {(4, 5, 6), (7, 8, 9), (1, 2, 3)}
字典生成式
与列表生成式类似。
例一、
my_dictionary = {'customer1': 7, 'customer2': 9, 'customer3': 11}
my_results = {key: value for key, value in my_dictionary.items() if value > 10}
print("Output #3 (dictionary comprehension): {}".format(my_results))
运行结果:
Output #3 (dictionary comprehension): {'customer3': 11}
例二、
import random
stuInfo = {'student' + str(i):random.randint(60,100) for i in range(20)}
print({name:score for name,score in stuInfo.items() if score > 90})
运行结果:
{'student0': 95, 'student1': 97, 'student2': 93, 'student6': 92, 'student14': 99, 'student16': 92, 'student17': 98}