a_range = range(10)
# 对a_range执行for表达式
a_list = [x * x for x in a_range]
# a_list集合包含10个元素
print(a_list)
# [0 , 1 , 4 , 9 , 16 , 25 , 36 , 49 , 64, 81]
b_list = [x * x for x in a_range if x % 2 == 0]
# a_list集合包含5个元素
print(b_list)
# [0 ,4 , 16, 36, 64]
d_list = [(x, y) for x in range(5) for y in range(4)]
# d_list列表包含20个元素
print(d_list)
# [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3), (4, 0), (4, 1), (4, 2), (4, 3)]
# ---------------等价于---------------
dd_list = []
for x in range(5):
for y in range(4):
dd_list.append((x, y))
# [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3), (4, 0), (4, 1), (4, 2), (4, 3)]
a=['零' if i==0 else '三' if i==3 else '五' if i==5 else i for i in range(10) ]
print(a)
# ---------------------等价于-------------------
for i in range(10):
if i==0:
print('零')
else:
if i==3:
print('三')
else:
if i==5:
print('五')
else:
print(i)
systax :
[exp1 if con1 else exp2 if con1 else exp3 for data1 in iterable_data1 for data2 in iterable_data2]
示例:
list_x = [10,1]
list_y = [1,8]
print([x if x>y else y if y>x else 'eq' for x in list_x for y in list_y])
# [10, 10, 'eq', 8]
一般来说多层if else语句放在一边,for语句放在另一边,尽可能别交叉放置,极可能出现错误。
[exp for x in data if condition]
# 只能存在一个表达式exp
[exp1 if condition else exp2 for x in data]
# 允许存在2个表达式exp,相对形式1更加强大和灵活,对于不满足条件的数据也能得到处理
源于:python列表推导式中使用if-else_jasonLee_lijiaqi的博客-CSDN博客_if 列表推导式
#1-100中3的倍数
p = [x for x in range(1,101) if x%3 == 0]
#1-100中,不是3的倍数的数去相反数,其余的数保持不变
q = [x if x%3==0 else -x for x in range(1,101)]
[exp1 if con1 else exp2 if con1 else exp3 for data1 in iterable_data1 for data2 in iterable_data2]
list_x = [10,1]
list_y = [1,8]
print([x if x>y else y if y>x else 'eq' for x in list_x for y in list_y])
# [10, 10, 'eq', 8]
我觉得最主要的还是学会画圈圈,哪些是一个局部的小整体,这些小整体之间是什么关系?