2015-04-05 60 views
1

我需要幫助找到一個python函數,它只會顯示元組中的值,(x)次數。python只顯示循環中的元組元素x的時間量

from random import * 


rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King") 

suit = ("hearts", "diamonds", "spades" , "clubs") 

users = ("I", "computer", "deck") 

NUMCARDS = 52 
DECK = 0 
PLAYER = 1 
COMP = 2 

count = 0 
while (count < 52): 
    for u in rankName: 
     for i in suit: 
      count = count + 1 
      w = choice(users) 
      ''' 'computer' and 'I' should only show 5 times, while deck shows 42 cards ''' 
      print count, '\t| ', u,' of', i, '\t|', w 

感謝。

+0

你沒有的功能,雖然/ – khajvah 2015-04-05 17:12:04

+0

對不起,我的意思方法......我試過數(),但它只會從元組中打印出現一次,從元組中循環1個值。 – SicLeaf 2015-04-05 17:21:49

+0

while循環是多餘的。它會在沒有它的情況下循環適當的時間。 – 2015-04-05 17:35:25

回答

0

添加兩行,試試吧:

from random import * 


rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King") 

suit = ("hearts", "diamonds", "spades" , "clubs") 

users = ("I", "computer", "deck") 

# make it weighted and shuffed 
users_with_weights = ["I"]*5 + ['computer']*5 + ['deck']*42 
shuffle(users_with_weights) 

NUMCARDS = 52 
DECK = 0 
PLAYER = 1 
COMP = 2 

count = 0 
while (count < 52): 
    for u in rankName: 
     for i in suit: 
      count = count + 1 
      w = users_with_weights.pop() 
      ''' 'computer' and 'I' should only show 5 times, while deck shows 42 cards ''' 
      print count, '\t| ', u,' of', i, '\t|', w 

讓我知道,如果它滿足您的所有需求。

+0

你有魔力,謝謝。 – SicLeaf 2015-04-05 17:43:25

0

你也可以有所變化你的邏輯和實際發牌,如:

from itertools import product 
from random import * 
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", 
      "Nine", "Ten", "Jack", "Queen", "King") 
suit = ("hearts", "diamonds", "spades" , "clubs") 
users = ("deck", "I", "computer") 

NUMCARDS = 52 
DECK = 0 
PLAYER = 1 
COMP = 2 

deck = list(product(suit, rankName)) 
deal = sample(deck, 10) 
player = deal[0::2] 
computer = deal[1::2] 

for count, (suit, rank) in enumerate(deck): 
    user = PLAYER if (suit, rank) in player else COMP if (suit, rank) in computer else DECK 
    print count+1, '\t| ', rank,' of', suit, '\t|', users[user]