我试图得到答案m = [0, 2, 0, 4, 0]:
m = []
while True:
for x in range(1, 6):
if x == 2:
m.append(x)
continue
else:
m.append(0)
continue
if x == 4:
m.append(x)
continue
else:
m.append(0)
continue
break
print(m)
Run Code Online (Sandbox Code Playgroud)
答案来了m = [0, 2, 0, 0, 0]
主要问题是你需要使用elif. 您也不需要 while 循环。
m = []
for x in range(1, 6):
if x == 2:
m.append(x)
elif x == 4:
m.append(x)
else:
m.append(0)
print(m)
Run Code Online (Sandbox Code Playgroud)
但这看起来确实是你需要做的就是检查该值是否能被 2 整除:
m = []
for x in range(1, 6):
if x % 2 == 0:
m.append(x)
else:
m.append(0)
print(m)
Run Code Online (Sandbox Code Playgroud)
通过列表理解:
print([x if x % 2 == 0 else 0 for x in range(1, 6)])
Run Code Online (Sandbox Code Playgroud)