![](/img/trans.png)
[英]How do I append items to a list inside a for loop in python?
[英]Python - How do I append numbers inside the list and
每當我嘗試將輸入中的數字附加到列表中時,它就會放在括號之一之外而不是兩個括號之內
有沒有辦法只有一對而不是兩個?
我也試圖在1-3之間添加隨機數,然后得到
[[2, 1, 3]]
如何在十分之一的小數位中創建隨機數
我的密碼,
import random
array = []
nums = random.sample(range(1, 4), 3)
array.append(nums)
print(array)
for x in range(2):
nums = int(input("what are your numbers "))
array.append(nums)
print(array)
我明白了
[[2, 1, 3]]
what are your numbers 3
[[2, 1, 3], 3]
what are your numbers 2
[[2, 1, 3], 3, 2]
Process finished with exit code 0
random.sample()已經將列表作為返回值返回給您,因此無需將其附加到另一個
array = random.sample(range(1, 4), 3)
在你的代碼中
import random
array = random.sample(range(1, 4), 3)
print(array)
for x in range(2):
number = int(input("what are your numbers "))
array.append(number)
print(array)
首先,讓nums為列表nums = random.sample(range(1, 4), 3)
。 因此,如果將nums追加到array,則該數組將成為一個包含其他列表而不是整數的列表。
也許你可以簡單地嘗試array = random.sample(range(1, 4), 3)
它將讓array為一個整數列表,然后附加您需要的其他數字。
實際上,還有另一種方法可以執行所需的操作,只需array += random.sample(range(1, 4), 3)
,它將把random.sample中的內容追加到數組中,而不是作為列表追加。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.