簡體   English   中英

打印用戶輸入范圍內的數組

[英]Print an array in the range of a user input

下面是我的代碼:

 n = int(input())

 for i in range(n):

    d = int(input())

    for i in range(d):
        a = list(map(int,input().split()))
    print(a)

但我希望我的代碼能夠做到這一點,例如:假設d = 4是我的用戶輸入 現在,我想要(隨機示例) a = [1, 4 , 8, 19] 這也來自用戶輸入。 這是輸出的一個例子。 我無法正確地提出問題。 因此,這是所需的輸出:

3 #輸入n

2 #輸入為d

[4,6] #輸出一個

5 #第二個d的輸入

[4,2,1,4,7] #output for a, 5 個元素為 d = 5

2 #輸入最后一個 d,因為 'n' 是 3

[1,9] #(最后一個數組a)

您的代碼可以簡化。 您似乎正在嘗試結合以下兩種截然不同的數據收集方法。 您應該選擇其中之一。

個人參賽作品

n = int(input('How many numbers?\n'))

res = []
for i in range(1, n+1):
    res.append(int(input('Enter number{0}\n'.format(i))))

同時參賽

n = int(input('How many numbers?\n'))

in_str = input('Enter the numbers separated by space:\n')

res = list(map(int, in_str.split()))

你的代碼有問題

  • 您在兩個 for 循環中都使用相同的i變量
  • a = list(map(int,input().split()))掃描整行,所以不需要 for 循環

解決方案

n = int(input())

for i in range(n):

    d = int(input())

    a = list(map(int,input().split()))
    print(a)

輸出

2
5
1 2 3 4 5
[1, 2, 3, 4, 5]  # Output
2   
1 2
[1, 2]  # output

如果你得到你的答案,請接受它,否則評論有什么問題?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM