当我运行这个程序时:(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'...
此外,这是基于猜猜游戏的大型程序的一部分...... 有人可以告诉我如何解决这个问题吗? THX
答案 0 :(得分:3)
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个随机选项,最好 shuffle people
列表,然后将该列表的前6个添加到{{ 1}}:
group
但是当然你有可能在某个时候再次出现一个空列表。
另一种方法是使用random.sample()
:
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
这只会从列表中选择6个随机名称,但people = 'Alice Elise Jack Jill Ricardo David Jane Sacha Thomas'.split()
group.extend(random.sample(people, 6))
不会受到影响,未来的6个名称可能会重复名称。