目前代碼:Python 3裏將無法正常工作
import random
numbers=[]
for i in range(20):
spam = random.randint(1,30)
print(spam)
我想插入spam
到numbers
但是這是我在哪裏卡住了。
預期結果:
20張隨機數
目前代碼:Python 3裏將無法正常工作
import random
numbers=[]
for i in range(20):
spam = random.randint(1,30)
print(spam)
我想插入spam
到numbers
但是這是我在哪裏卡住了。
預期結果:
20張隨機數
你幾乎在那裏,但不是隻是打印你的隨機數,你需要把它附加到你的清單numbers
。只需將行numbers.append(spam)
添加到您的for
循環的正文。
(你可以刪除打印語句,如果你不需要了。)
有更優雅的方式來構建這個列表(見列表理解的答案),但在你的水平append
是好的。
使用此代碼清單
import random
numbers=[]
for i in range(20):
spam = random.randint(1,30)
numbers.append(spam)
print numbers
輸出
[14, 19, 5, 20, 17, 8, 7, 28, 18, 3, 26, 9, 10, 15, 28, 20, 8, 26, 13, 16]
你可能會有所不同,因爲它們是隨機數
另外,您可以使用列表理解:
numbers = [random.randint(1, 30) for _ in range(20)]
import numpy as np
import random
# np.random.randint can take 3 arguments low, high and size.
# In this case an array of 20 (size) random integers from range 1 (low) to 30 (high)
# will be printed. The range is inclusive of 1 and exclusive of 30.
spam = np.random.randint(1,30,20); print(spam)
[ 5 12 16 19 27 19 27 9 12 2 21 7 7 12 4 13 4 28 21 5]
'numbers.append(垃圾郵件)''的循環for'內是你在找什麼。 – asongtoruin
您的列表是「數字」,而不是「垃圾郵件」。你說你沒有找到任何關於如何填寫Python列表的指南? –