[英]Print array elements in reverse order
第一行包含一個整數 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
您正在通過刪除空格並拆分' '
處的值來創建整數值列表。 獲得整數列表后,您將遍歷列表並將 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.
在 pyton-3 中
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
讓我們拿這個代碼片段
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()
后返回一個字符串列表。這里的分隔符是空格。 所以, 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
。
上面的代碼可以改寫成下面這樣,更具可讀性。
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 文檔。
嘗試這個!
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.