python only show tuple items in loop x amount of times

青春壹個敷衍的年華 提交于 2019-12-11 11:51:25

问题


I need help finding a python function that will only show the value in the tuple, (x) amount of times.

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

thanks.


回答1:


Add two lines, try it:

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

Let me know if it meets all your needs.




回答2:


You could also change your logic somewhat and actually deal the cards, e.g.:

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]


来源:https://stackoverflow.com/questions/29459803/python-only-show-tuple-items-in-loop-x-amount-of-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!