[英]“ValueError: list.remove(x): x not in list”, due to random numbers?
I'm writing a function to take a new card from a deck of cards, given that there are already some cards out of the deck. 我正在编写一个函数来从一副纸牌中取出一张新纸牌,因为已经有一些纸牌在外面。
def trekken(getrokken = []):
import itertools
import random
getrokken = list(getrokken)
kind = 'HCDS'
value = '123456789XJQKA'
deck = ["".join(card) for card in itertools.product(value,kind)]
for i in range(0, len(getrokken)-1): deck.remove(getrokken[i])
return(deck[(random.randint(1, len(deck)))])
When I use this for some examples a few times I sometimes get the error message: 当我多次使用此示例时,有时会收到错误消息:
line 16, in trekken
print(deck[(random.randint(1, len(deck)))])
IndexError: list index out of range
For example with the following input: 例如,使用以下输入:
trekken(['6H', '3C', '3D', '8C', 'AD', '9D', '7D', 'QC'])
Maybe not the first time, but after a few tries (max. 20) I always get this error message. 也许不是第一次,但是经过几次尝试(最多20次)后,我总是收到此错误消息。
In Python random.randint(low, high)
will also yield high
, thus len(deck)
might not be a good candidate for high, better choose a value smaller by one so try instead as last line: 在Python中
random.randint(low, high)
也会产生high
,因此len(deck)
可能不是high的理想候选者,最好选择一个小一个的值,因此尝试作为最后一行:
return deck[random.randint(0, len(deck)-1)]
Or even more clear - as @jonrsharpe suggests: 甚至更清楚-如@jonrsharpe建议:
return deck[random.randrange(len(deck))]
... or as Martijn Pieters suggests: ...或Martijn Pieters建议:
return random.choice(deck)
Note: The list index in Python starts at 0
not 1
as in other languages like R
. 注意:Python中的列表索引从
0
而不是1
开始,就像其他语言(如R
一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.