2017-04-11 118 views
0

目前代码:Python 3里将无法正常工作

import random 
numbers=[] 
for i in range(20): 
    spam = random.randint(1,30) 
    print(spam) 

我想插入spamnumbers但是这是我在哪里卡住了。

预期结果:

20张随机数

+1

'numbers.append(垃圾邮件)''的循环for'内是你在找什么。 – asongtoruin

+0

您的列表是“数字”,而不是“垃圾邮件”。你说你没有找到任何关于如何填写Python列表的指南? –

回答

2

你几乎在那里,但不是只是打印你的随机数,你需要把它附加到你的清单numbers。只需将行numbers.append(spam)添加到您的for循环的正文。

(你可以删除打印语句,如果你不需要了。)

有更优雅的方式来构建这个列表(见列表理解的答案),但在你的水平append是好的。

1

使用此代码清单

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] 

你可能会有所不同,因为它们是随机数

1

另外,您可以使用列表理解:

numbers = [random.randint(1, 30) for _ in range(20)] 
0
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]