Python - 如何添加随机数列表?

时间:2015-04-06 02:55:18

标签: list python-3.x random

您好!编码人员!

有人有个好主意在列表中添加一个随机数吗?我想获取一个列表来记录循环内生成的随机数。以下是循环内部代码的示例:

stuff = {'name': 'Jack', 'age': 30, 'height': '6 foot 9 inches'}

tester = [0]

print(tester)

tester.append[random.randint(1, len(stuff))]

print(tester)

显然random.randint的输出不是可下载的,但我不确定如何写这个。

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

tester.append[random.randint(1, len(stuff))]
#      wrong ^                       wrong ^

# should be
tester.append(random.randint(1, len(stuff)))

使用括号而不是括号来调用append等方法。

答案 1 :(得分:0)

这很简单,试试这个

from random import randint # import randint from random
listone = [] # Creating a list called listone
for i in xrange(1,10): # creating a loop so numbers can add one by one upto 10 times
   ic = randint(1,10) # generating random numbers from 1 to 10
   listone.append(ic) # append that numbers to listone
   pass
print(listone) # printing list
# for fun you can sort this out ;)
print(sorted(listone))

答案 2 :(得分:0)

在您的代码中进行此修改

import random
stuff = {'name': 'Jack', 'age': 30, 'height': '6 foot 9 inches'}

tester = [0]

print(tester)

tester.append(random.randint(1, len(stuff)))

print(tester)