POKERHANDS - 如何在使用后从列表中删除

时间:2018-04-08 16:29:21

标签: python arrays poker

我有那个代码。如果我输入n参数是3,它将是3手。 但我想只用一次卡。 完全有52张牌。每张卡只能使用一次。 如何在使用后删除卡片?

顺便说一句,stdio.writeln就像打印一样。一样。

n = int(sys.argv[1])

SUITS = ["Clubs", "Diamonds", "Hearts", "Spades"]
RANKS = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen",
         "King", "Ace"]


rank = random.randrange(0, len(RANKS))
suit = random.randrange(0, len(SUITS))


deck = []
for rank in RANKS:
    for suit in SUITS:
        card = rank + " of " + suit
        deck += [card]

for i in range(n):
    a = len (deck)

    for i in range(a):
        r = random.randrange(i, a)
        temp = deck[r]
        deck[r] = deck[i]
        deck[i] = temp

    for i in range(5):
        stdio.writeln(deck[i] + " ")
    stdio.writeln()

1 个答案:

答案 0 :(得分:0)

利用List comprehenshion组成一大堆卡片, 使用random.sample()从中获取混合卡的副本,然后通过list.pop()提取卡片,这将自动删除卡片。

我缩短了RANKS以缩短打印输出:

SUITS = ["Clubs", "Diamonds", "Hearts", "Spades"]
RANKS = ["2", "3", "4", "5", "6"] #,'7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]

import random
# in order
StackOfCards = [ f'{r} of {s}' for r in RANKS for s in SUITS]

# return random.sample() of full length input == random shuffled all cards 
mixedDeck = random.sample(StackOfCards, k = len(StackOfCards))

print("Orig:",StackOfCards)
print()
print("Mixed:",mixedDeck)
print()

# draw 6 cards into "myHand" removing them from "mixedDeck":
myHand = [mixedDeck.pop() for _ in range(6)]

print("Hand:",myHand) 
print()
print("Mixed:",mixedDeck)

输出:

Orig: ['2 of Clubs', '2 of Diamonds', '2 of Hearts', '2 of Spades', '3 of Clubs', 
       '3 of Diamonds', '3 of Hearts', '3 of Spades', '4 of Clubs', '4 of Diamonds', 
       '4 of Hearts', '4 of Spades', '5 of Clubs', '5 of Diamonds', '5 of Hearts', 
       '5 of Spades', '6 of Clubs', '6 of Diamonds', '6 of Hearts', '6 of Spades']

Mixed: ['2 of Clubs', '3 of Diamonds', '6 of Hearts', '4 of Spades', '5 of Clubs', 
        '3 of Hearts', '6 of Spades', '5 of Hearts', '4 of Diamonds', '3 of Spades', 
        '2 of Spades', '6 of Clubs', '4 of Clubs', '5 of Spades', '6 of Diamonds', 
        '2 of Diamonds', '3 of Clubs', '2 of Hearts', '5 of Diamonds', '4 of Hearts']

Hand: ['4 of Hearts', '5 of Diamonds', '2 of Hearts', 
       '3 of Clubs', '2 of Diamonds', '6 of Diamonds']

Mixed: ['2 of Clubs', '3 of Diamonds', '6 of Hearts', '4 of Spades', '5 of Clubs', 
        '3 of Hearts', '6 of Spades', '5 of Hearts', '4 of Diamonds', '3 of Spades', 
        '2 of Spades', '6 of Clubs', '4 of Clubs', '5 of Spades']

使用.pop()减少了删除内容的需要,如果你真的不喜欢它(为什么会这样?)你可以通过以下方式重新创建一个没有其他列表元素的列表:

l = [1,2,3,4,5,6]
p = [2,6]
l[:] = [ x for x in l if x not in p] # inplace modifies l to [1,3,4,5]