Python推导式
""" 列表推导式 [表达式 for item in 可迭代对象] 或 [表达式 for item in 可迭代对象 if 条件判断] """ a = [x*2 for x in range(5)] print(a) # [0, 2, 4, 6, 8] a = [] for x in range(5): a.append(x*2) print(a) a = [x*2 for x in range(5) if x % 2 == 0] print(a) # [0, 4, 8] a = [] for x in range(5): if x % 2 == 0: a.append(x*2) print(a) cells = [(row, col) for row in range(1, 3) for col in range(1, 3)] # 两层循环 print(cells) # [(1, 1), (1, 2), (2, 1), (2, 2)] cells = [] for row in range(1, 3): for col in range(1, 3): cells.append((row, col)) print(cells)
"""
字典推导式格式: 哈希表(用数组实现的)
{key_expression: value_expression for 表达式 in 可迭代对象}
还可以添加if判断语句
"""
text = "I love you, Can you marry me ?"
dic = {c:text.count(c) for c in text}
print(dic) # {'I': 1, ' ': 7, 'l': 1, 'o': 3, 'v': 1, 'e': 2, 'y': 3, 'u': 2, ',': 1, 'C': 1, 'a': 2, 'n': 1, 'm': 2, 'r': 2, '?': 1}
dic = {}
for c in text:
dic[c] = text.count(c)
print(dic)
"""
集合推导式
{key_expression for 表达式 in 可迭代对象} 集合的本质是字典,没有值只有键的字典
"""
a = [2,3,2,3,5,67,5]
b = {x for x in a}
print(b) # {67, 2, 3, 5}
"""
生成器推导式 (生成元组) 只能使用一次
(表达式 for 对象 in 可迭代对象)
"""
a = (x**2 for x in range(10) if x % 2 == 0)
print(list(a)) # [0, 4, 16, 36, 64]
a = (x**2 for x in range(10) if x % 2 == 0)
for i in a:
print(i, end=" ")