在列表中使用random.choice
,但首先从列表中删除该特定数字:
>>> import random
>>> n = 3
>>> end = 5
>>> r = range(1,n) + range(n+1, end)
>>> r
[1, 2, 4]
>>> random.choice(r)
2
>>> random.choice(r)
4
或者定义一个函数:
def func(n, end, start = 1):
return range(start, n) + range(n+1, end)
...
>>> r = func(3, 5)
>>> r
[1, 2, 4]
>>> random.choice(r)
2
更新:
这将返回列表中除特定数字之外的所有数字:
>>> r = range(5)
for player in r:
others = range(0, player) + range(player+1, 5)
print player,'-->', others
...
0 --> [1, 2, 3, 4]
1 --> [0, 2, 3, 4]
2 --> [0, 1, 3, 4]
3 --> [0, 1, 2, 4]
4 --> [0, 1, 2, 3]