list, set, dict, generator comprehension
list comprehension:
my_list = [num*num for num in range(1,11)] print(my_list)
if使用
my_list = [num for num in range(1,11) if num > 5] print(my_list)
if在for循环后面
if else使用
my_list = [num if num < 5 else 'larger' for num in range(1,11) ] print(my_list)
if在for循环前面
set comprehension与list comprehension类似,区别在于list使用的是[],而set得用()
例如:
my_list = [1,1,1,2,2,3,3,3,3,4,4,7,7,7,9,9,9,9] my_set = {num for num in my_list} print(my_set)
结果为:
{1, 2, 3, 4, 7, 9}
dict comprehension:
简单易懂的方法:
names = ['peter', 'clark', 'wade', 'bruce', 'logan'] heros = ['spideman', 'superman', 'deadpool', 'batman', 'wolverine'] my_dict = {} for name, hero in zip(names, heros): my_dict[name] = hero print(my_dict)
dict comp:
names = ['peter', 'clark', 'wade', 'bruce', 'logan'] heros = ['spideman', 'superman', 'deadpool', 'batman', 'wolverine'] my_dict = {name: hero for name, hero in zip(names, heros)} print(my_dict)
结果都是:
{'peter': 'spideman', 'clark': 'superman', 'wade': 'deadpool', 'bruce': 'batman', 'logan': 'wolverine'}
generator comprehension:
注意:
上面的list用的是[];
dict用的是{}
set用的也是{},区别是没有:
而generator用的是()
my_gen = (num for num in range(1,11)) for item in my_gen: print(item)