这是一个扑克应用程序(练习/我正在创建的第一个应用程序)。第一个函数创建一张卡片,第二个函数创建一个Hole(德州扑克中的前2张牌)。我试图让第二个函数调用第一个函数,检查重复,然后返回2个卡(由RANK中的2个项和SUIT中的2个组成)。它返回超过2张牌,我不知道为什么。
它在输出中返回两个列表。其中2个是重复的,但我不知道是不是我在第一个有错误的函数中附加它们的方式。
#!/usr/bin/python3
from random import choice
from random import randint
class Cards(object):
RANK = [1,2,3,4,5,6,7,8,9,10,'J','Q','K','A']
SUIT = ['Club','Diamond','Heart','Spade']
#Creates One random card/suit combo
def picker(self):
pick=[]
pick.append(choice(self.RANK))
pick.append(choice(self.SUIT))
return pick
#'Should' create 2 cards, check that they aren't dupes, and return them.
def hole(self):
hold=[]
nodup=[]
while len(hold)<5:
nodup.append(self.picker())
if nodup not in hold:
hold.append(nodup)
else:
hold.append(self.picker())
continue
return hold
当我调用该函数时,我得到了这个 -
>>> from cards import Cards
>>> test=Cards().hole()
>>> test
[[[2, 'Heart'], ['Q', 'Spade'], [2, 'Diamond'], [9, 'Club'], [1, 'Diamond']], [5, 'Heart'], [5, 'Heart'], [5, 'Club'], ['K', 'Heart']]
I want-
>>> [2, 'Heart'], ['Q', 'Spade']
答案 0 :(得分:3)
你最好只是创造更接近一副纸牌的东西。例如,您可以使用itertools.product
创建所有单独的卡片,random.shuffle
将其混合起来,并list.pop
一次处理一张卡片:
In [46]: from itertools import product
In [47]: from random import shuffle
In [48]: RANK = [1,2,3,4,5,6,7,8,9,10,'J','Q','K','A']
In [49]: SUIT = ['Club','Diamond','Heart','Spade']
In [50]: cards = list(product(RANK, SUIT))
In [51]: shuffle(cards)
In [52]: cards.pop()
Out[52]: (3, 'Spade')
In [53]: cards.pop()
Out[53]: (10, 'Club')
In [54]: len(cards)
Out[54]: 54
另外,看看最后的长度 - 你的队伍中有1和A都有。
答案 1 :(得分:1)
这是一种更简单的方式来获得你想要的东西:
def hole(self):
hold=[]
# Pick two cards
hold.append(self.picker())
hold.append(self.picker())
# Make sure the cards aren't the same
while hold[0]==hold[1]:
hold[1] = self.picker()
return hold
尽管正如Randy C指出的那样,有更好的方法可以做到这一点。