3

当我运行这个程序时:(python 3.3.1)

import random
import time
from random import randrange
print(' ')
print('I am thinking of a person...')
time.sleep(1)
print('He or she belongs to this group of people:')
people = 'Alice Elise Jack Jill Ricardo David Jane Sacha Thomas'.split()
loop = 0
while loop != 6:
    group = []
    person = randrange(0, len(people))
    personName = people[person]
    int(person)
    group.append(personName)
    del people[person]
    loop = loop + 1

我有时会收到此错误消息:

Traceback (most recent call last):
  File "C:\Users\user\Python\wsda.py", line 132, in <module>
    person = randrange(0, len(people))
  File "C:\Python33\lib\random.py", line 192, in randrange
    raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop,     width))
ValueError: empty range for randrange() (0,0, 0)

基本上我希望它从变量'people'中获取6个随机名称并将其添加到变量'group'中......

这也是基于猜测谁游戏的更大程序的一部分......有人可以告诉我如何解决这个问题吗?谢谢

4

1 回答 1

5

people列表为空(长度为 0)时发生错误。您可能需要对此进行测试:

>>> import random
>>> random.randrange(0, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/random.py", line 217, in randrange
    raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (0,0, 0)

如果您需要从people列表中添加 6 个随机选项,最好将列表打乱people然后将该列表的前 6 个添加到group

import random

people = 'Alice Elise Jack Jill Ricardo David Jane Sacha Thomas'.split()
random.shuffle(people)
group.extend(people[:6])
people = people[6:]  # remainder, so the 6 picks have been removed

但是你当然有可能在某个时候再次得到一个空列表。

另一种方法是只使用random.sample()

people = 'Alice Elise Jack Jill Ricardo David Jane Sacha Thomas'.split()
group.extend(random.sample(people, 6))

这只是从列表中选择 6 个随机名称,但people不受影响,未来选择 6 个名称可能会重复名称。

于 2013-08-10T11:43:34.697 回答