【问题标题】:How to convert the output into a single line [closed]如何将输出转换为单行[关闭]
【发布时间】:2021-11-21 22:18:25
【问题描述】:
#python
n = int(input().strip())
arr = list(map(int, input().rstrip().split()))

rev=arr[::-1]
for i in range(n):
    final=0
    final+=rev[i]
    print(final)

给定一个整数数组,将元素以相反的顺序打印为一行以空格分隔的数字。

【问题讨论】:

    标签: python arrays python-3.x list


    【解决方案1】:

    你可以使用连接方法来连接字符串序列

    但在您的情况下,您需要将整数转换为字符串类型

    最后的代码是这样的: reversed_string = ' '.join(map(str, rev))

    【讨论】:

      【解决方案2】:

      您多次调用input() 这不是必需的,您也可以使用join 函数和" " 分隔符在一行中打印数组的所有元素。请注意join 期望所有元素都为str,因此您必须将map 它返回到str,因此最好在初始阶段避免mapint,因为我们必须这样做mapstr
      这是其中一种方法:

      n = input("Enter the sequence of numbers: ").strip()
      arr = n.split()
      print (" ".join(arr[::-1]))
      

      输出:

      Enter the sequence of numbers: 1 3 5 7 9
      9 7 5 3 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-27
        • 1970-01-01
        • 2011-05-02
        • 2020-03-27
        相关资源
        最近更新 更多