[英]How to to print this output in Python [top down (even)] [bottom up (odd)]
Trying to print this pattern of numbers want this output:(if a=10)尝试打印此数字模式需要此输出:(如果 a=10)
2
9
4
7
6
5
8
3
10
1
CODE::代码::
a=10
for i in range(1,a+1):
if(i%2==0):
print(i)
elif(a-i%2!=0):
print(a-i)
As you starts form 2
I'd suggest the loop do the same, then depending if the value if odd or even, print the good things当你从表格
2
开始时,我建议循环做同样的事情,然后根据值是奇数还是偶数,打印好东西
a = 10
for i in range(2, a + 2):
if i % 2 == 0:
print(i)
else:
print(a - i + 2)
Have no idea what this problem is about, but keeping to your approach your style of code, you just need to flip every other value about, so:不知道这个问题是关于什么的,但保持你的代码风格,你只需要翻转所有其他值,所以:
a=10
for j in range(1,a+1):
i = j + 1 if j % 2 else j - 1
if(i%2==0):
print(i)
elif(a-i%2!=0):
print(a-i)
Another solution would be to run multiple iterators and run through them both:另一种解决方案是运行多个迭代器并同时运行它们:
a = 10
for i, j in zip(range(2, a + 2), range(a, 0, -1)):
print(j if i % 2 else i)
Or you can create a single list with all the items:或者您可以创建一个包含所有项目的列表:
a = 10
print([i for l in zip(range(2, a + 2, 2), range(a - 1, 0, -2)) for i in l])
The first range
runs through the list forwards, and the second range
runs backwards in each case.在每种情况下,第一个
range
向前遍历列表,第二个range
向后运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.