list comprehension and if..else...
已知数据为:
test_list = range(1, 10)
问题是将该数据中偶数取1,奇数为0?
for循环操作如下:
result_list = list()
for i in test_list:
if i % 2 == 0:
result_list.append(1)
else:
result_list.append(0)
list解析式
通过列表解析式,我们以如下方式写,可以返回偶数的数量并且每位赋值为1。
[1 for i in test_list if i % 2==0]
# [1, 1, 1, 1]
但为了满足问题需求,需要做如下变动:
[1 for i in test_list if i % 2 == 0 else 0]
运行以上代码,会发现报错,即这样的形式是错误的,正确的方式应该如下:
[1 if i % 2==0 else 0 for i in test_list]
# [0, 1, 0, 1, 0, 1, 0, 1, 0]
正确和错误的形式你区分清楚了吗?










