【问题标题】:Print array elements in reverse order以相反的顺序打印数组元素
【发布时间】:2019-06-25 15:39:01
【问题描述】:

第一行包含一个整数 N,(我们数组的大小)。 第二行包含 N 个用空格分隔的整数,描述数组 (A) 的元素。

我尝试了以下方法,但是我查看了解决方案页面。但是我不明白这段代码是如何工作的。有人可以向我解释一下。我是这个编码世界的新手。

import math
import os
import random
import re
import sys

if __name__ == '__main__':
    n = int(input())
    arr = [int(arr_one) for arr_one in input().strip().split(' ')]
    for i in range(len(arr)):
        print(str(arr[-i-1]), end = " ")

输入 1234 输出 4 3 2 1

【问题讨论】:

  • 输入不是空格分隔的。输入正确吗?

标签: arrays python-3.x string


【解决方案1】:

在 Python3 中:

if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().rstrip().split()))
    print(" ".join(str(x) for x in arr[::-1]))

输入:

1 4 3 2

输出:

2 3 4 1

【讨论】:

    【解决方案2】:

    您正在创建一个整数值列表,方法是删除空格并拆分' ' 处的值。在获得整数列表后,您将遍历列表并将 arr 后面的第 i 个元素(index 的负值表示从右边开始的第 i 个索引的元素,它基于 1)转换回字符串并打印数字。

    例子:

     arr = [1,2,3,4]
     print(arr[1])  #prints 2 on the console, i.e 2nd element from the left.
     print(arr[-1]) #prints 4 on the console, i.e 1st element from the right.
    

    【讨论】:

    • 如果这有帮助,您可以点赞,这样它也可以对其他人有所帮助。
    【解决方案3】:

    让我们用这段代码sn-p

    n = int(input())
    arr = [int(arr_one) for arr_one in input().strip().split(' ')]
    for i in range(len(arr)):
        print(str(arr[-i-1]), end = " ")
    

    input() 方法将从键盘获取用户输入。如果输入是字符串格式,int(input()) 会将输入转换为 int。像“4”而不是4。输入值存储在变量n中。

    数组输入将像这样“1 2 3 4”。所以,我们需要用空格分隔字符串。

    strip() 方法返回删除了前导字符和尾随字符的字符串副本。

    split() 方法将给定的字符串用指定的分隔符打断后返回一个字符串列表。这里的分隔符是空格。所以,split(' ')

    input().strip().split(' ') 将“1 2 3 4”作为输入,输出为"1" "2" "3" "4"

    现在我们需要在分离后获取每个元素。然后转换成 int 并存储到数组中。

    arr = [int(arr_one) for arr_one in input().strip().split(' ')]
    

    arr_one是一个变量,这个变量存储了拆分后的每个元素。对于每个元素,我们将其转换为int,然后存储到数组arr

    在python中,数组索引从0开始。如果我们想从数组的最后一个索引开始访问,索引将从-1、-2、-3等开始。

    for i in range(len(arr)): for 循环将从索引 0 迭代到数组的长度。在此示例中,大小为 4。 从索引 -1 打印数组元素。 end 参数用于以给定字符结束print 语句,这里结束字符是" "。所以输出将是4 3 2 1

    【讨论】:

    • 非常感谢您花时间和精力解释!
    【解决方案4】:

    上面的代码可以改写如下,可读性更好。

    if __name__ == '__main__':
        n = int(input())
        inp = input("Enter the numbers seperated by spaces:::")
        inp = inp.strip() # To remove the leading and trailing spaces
        array = []
        for item in inp.split(' '):     # Splitting the input with space and iterating over each element
            array.append(int(item))     # converting the element into integer and appending it to the list
    
        print(array[::-1])  # here -1 says to display the items in the reverse order. Look into list comprehension for more details
    

    有关列表切片的更多详细信息,请查看 python 文档。

    【讨论】:

    • OP 要求对现有代码进行解释(这可能是故意避免切片),而不是“更好的方法”。这个答案有点没抓住重点。
    【解决方案5】:

    试试这个!

    if __name__ == '__main__':
    n = int(input()) # input as int from stream
    arr = [int(arr_one) for arr_one in input().strip().split(' ')]
    """
    1. asking for input from user
    2. strip() function removes  leading and trailing characters.
    3. split(' ') function split your input on space into list of characters
    4. arr_one variable contains yours splited character and your iterating over it using for loop
    5. int(arr_one) converts it into integer and  [] is nothing just storing everything into another list.
    6. In last you are assigning new list to arr variable
    """
    for i in reversed(arr): # loop over list in reverse order with built in fucntion
        print(i, end = " ") # printing whatever comes in i
    

    它应该像这样工作:

    3 # your n 
    1 2 3 # your input
    3 2 1 # output
    

    【讨论】:

    • OP 要求解释现有代码,而不是改进代码。
    猜你喜欢
    • 2016-02-18
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2021-08-23
    相关资源
    最近更新 更多