列表推导还原问题
将下列代码还原>>> list1 = [(x, y) for x in range(10) for y in range(10) if x%2==0 if y%2!=0]
答案:
list1 = []
for x in range(10):
for y in range(10):
if x%2 == 0 and y%2 != 0:
list1.append((x,y))
哪里错了呢 为什么两个if之间是and? 你写的对着呢啊,我运行了,两个结果一样
本帖最后由 疾风怪盗 于 2020-9-14 19:40 编辑
list1 = []
for x in range(10):
for y in range(10):
if x % 2 == 0 and y % 2 != 0:
list1.append((x, y))
print(list1)
list2 = [(x, y) for x in range(10) for y in range(10) if x % 2 == 0 if y % 2 != 0]
print(list2)
[(0, 1), (0, 3), (0, 5), (0, 7), (0, 9), (2, 1), (2, 3), (2, 5), (2, 7), (2, 9), (4, 1), (4, 3), (4, 5), (4, 7), (4, 9), (6, 1), (6, 3), (6, 5), (6, 7), (6, 9), (8, 1), (8, 3), (8, 5), (8, 7), (8, 9)]
[(0, 1), (0, 3), (0, 5), (0, 7), (0, 9), (2, 1), (2, 3), (2, 5), (2, 7), (2, 9), (4, 1), (4, 3), (4, 5), (4, 7), (4, 9), (6, 1), (6, 3), (6, 5), (6, 7), (6, 9), (8, 1), (8, 3), (8, 5), (8, 7), (8, 9)]
都一样的 本帖最后由 heidern0612 于 2020-9-14 19:41 编辑
x和y不是并列关系。
list1 = [(x, y) for x in range(10) for y in range(10) if x%2==0 if y%2!=0]
等同于:
list1 = []
for x in range(10):
for y in range(10):
if x % 2 == 0:
if y % 2 != 0:
list1.append((x, y))
即使结果是一样的,但是内容不一样。 小甲鱼的铁粉 发表于 2020-9-14 19:34
你写的对着呢啊,我运行了,两个结果一样
是的,我把list1打印出来才发现是对的。。。直接F5没出结果我还以为是错了{:5_104:}
页:
[1]