第12讲,课后作业疑问
>>> 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))
我写的是这样
list2 = []
for x,y in range(10):
if x%2 == 0 and y%2 !=0:
list2.append((x,y))
程序会报错,是为什么呢?感谢大家解答 本帖最后由 jackz007 于 2021-10-21 21:42 编辑
不可以这样写
for x,y in range(10):
会语法错误
必须写成嵌套循环。
list2 = []
for x in range(10):
for y in range(10):
if x%2 == 0 and y%2 != 0:
list2.append((x,y))
print(list2)
运行实况
>>> list2 = []
>>> for x in range(10):
for y in range(10):
if x%2 == 0 and y%2 != 0:
list2.append((x,y))
>>> 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)]
>>>
jackz007 发表于 2021-10-21 21:26
不可以这样写
会语法错误
谢谢大佬
页:
[1]