随机的randint在for循环中不起作用

时间:2015-05-27 12:11:05

标签: for-loop random python-3.4

我正在尝试使用以下代码创建一个随机长度列表,其中填充了随机长度列表:

import random

solitaire = [None]*(random.randint(1,5)) 

for pile in solitaire:
    number = random.randint(0, 10)
    solitaire.append(number)    

print(solitaire)

我觉得很容易但是当我运行这段代码时,我的powershell窗口因为期待输入或其他东西而冻结,我不得​​不用ctr + c取消脚本然后收到消息:

Traceback (most recent call last):
File "sparakod.py", line 254, in <module>
number = random.randint(0, 10)
File "C:\Python34\lib\random.py", line 218, in randint
return self.randrange(a, b+1)
File "C:\Python34\lib\random.py", line 170, in randrange
def randrange(self, start, stop=None, step=1, _int=int):
KeyboardInterrupt

这是什么意思?为什么代码不会运行?

 number = random.randint(0, 10)

似乎工作得很好所以为什么不在for-loop中呢?

1 个答案:

答案 0 :(得分:1)

你没有对列表的内容说些什么,假设它们也包含随机整数,那么可能的解决方案如下:

"""
It creates a list with random length filled with lists of random lengths containing random integers

"""


import random

MIN_LIST_OF_LISTS_LENGTH = 1
MAX_LIST_OF_LISTS_LENGTH = 10

MIN_LIST_LENGTH = 1
MAX_LIST_LENGTH = 5

MIN_LIST_ELEMENT = 1
MAX_LIST_ELEMENT = 10


#This is the list which will containt all the lists
solitaire = list(range(random.randint(MIN_LIST_OF_LISTS_LENGTH,MAX_LIST_OF_LISTS_LENGTH)))


for i, pile in enumerate(solitaire):
    solitaire[i] = [
        random.randint(MIN_LIST_ELEMENT, MAX_LIST_ELEMENT) for x in
        range(0, random.randint(MIN_LIST_LENGTH, MAX_LIST_LENGTH))
    ]

print(repr(solitaire))

它将生成如下输出:

[[10, 3], [5, 2, 7, 7, 6], [5], [9, 3, 2, 6], [2, 4, 4], [4, 5, 10, 9, 10]]

[[5, 1], [5, 1, 1], [1, 1, 7, 3, 1]]

[[9, 1, 6, 7], [10, 7, 1, 7, 4]]