简体   繁体   English

如何在 Python 中打印此输出 [自上而下(偶数)] [自下而上(奇数)]

[英]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.

相关问题 如何将此自上而下的解决方案转换为自下而上的解决方案? - How to convert this top down solution to bottom up solution? 如何从 Python 中的给定字符串打印偶数和奇数字符 - How to print even and odd chars from a given string in Python 如何在 python 的终端顶部打印新的 output? - How to print new output at top of terminal in python? 使用 python 打印范围之间的奇数或偶数列表。 输出应与字符串在一行中 - Print the list of odd or even numbers between a range using python. Output should be in a single line along with the string Python 格式化输出偶数和奇数 - Python formatting output of even and odd numbers 用 Print 替换 python 字符串中的字符 - 奇数 output - Replacing a character in a python string - odd output with Print 如何打印偶数和奇数的计算结果? - How to print my calculations for even and odd integers? Python - 如何在第三个元素或第四个元素处按奇数和偶数对文本文件进行排序,并生成奇数或偶数条目的 output 文本文件 - Python - How to sort textfile by odd and even number at third element or fourth element and produce output textfiles of odd or even numbered entries print(print_board(board)) 的 output 如何像矩阵一样打印,而不像从上到下的列表或行? - how output of print(print_board(board)) is printed like a matrix but not like a list or line from top to bottom? "如何在python中打印奇数" - How to print odd numbers in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM