python randrange重复选择

时间:2016-06-05 17:24:29

标签: python random unique random-sample

如何确保每次在python中返回的值都是唯一的?我正在使用random.randrange如此 -

batter = ("Sammy Slammer","Lonnie Longball","Billy Bomber","Jack Runs","Ricky Redic",)
bnum = random.randrange(0,5)
upnow = batter[bnum]

除了经常重复之外,哪些有效..

感谢@Fabricator -

batter = ("Sammy Slammer","Lonnie Longball","Billy Bomber","Jack Runs","Ricky Redic",)
bnum = random.randrange(0,5)
upnow = batter[bnum]
l = list(batter)
random.shuffle(l)
for upnow in l:
print upnow

和 -

batter = ("Sammy Slammer","Lonnie Longball","Billy Bomber","Jack Runs","Ricky Redic",)
l = list(batter)
random.shuffle(l)
for upnow in l:
print upnow

错误即时反馈我的sqlite 3声明 -

"对于i在reverse(xrange)1中,len(x)int没有len()"

我缩短了代码,sqlite3在没有随机播放的情况下工作正常。

    bbatter_ai =  (brow["BATTER"])
tab = cab_ai + at_bat
conn.execute("UPDATE batter set AB = ? WHERE BATTER = ?",[tab] + [bbatter_ai])

1 个答案:

答案 0 :(得分:2)

你可以随机播放玩家名单:

l = list(batter)
random.shuffle(l)
for upnow in l:
    print upnow

IDLE:

In [1]: import random

In [2]: batter = ("Sammy Slammer","Lonnie Longball","Billy Bomber","Jack Runs","Ricky Redic",)

In [3]: l = list(batter)

In [4]: random.shuffle(l)

In [5]: for upnow in l:
   ...:     print upnow
   ...:     
Jack Runs
Sammy Slammer
Lonnie Longball
Billy Bomber
Ricky Redic