質問

私は52枚すべてのカードをセットアップしています、そして私は52枚すべてのカードを使用して印刷しようとします for loop。設定する方法がわかりません for loop この時点で。

def define_cards(n):
    rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king")
    suit_string = ("clubs","diamonds","hearts","spades")
    cards = []
    for suit in range(4):
        for rank in range(13):
            card_string = rank_string[rank] + " of " + suit_string[suit]
            cards.append(card_string)

print "The cards are:"
for i in range(52):              #how to make this for loop work??
    print i, card_string[i]

このように印刷したいです

The crads are:
0 ace of clubs
1 two of clubs
2 three of clubs
...
49 jack of spades
50 queen of spades
51 king of spades
役に立ちましたか?

解決

あなたの機能 define_cards リストを返す必要があります。追加 return cards その最後に。

その後、実際にこの関数を呼び出す/実行する必要があります。

次に、このリストの個々のカードにアクセスできます。

cards = define_cards()
for i, card in enumerate(cards):
    print i, card

ただし、「より多くのpythonic」ソリューションを探している場合は、これを試してください。

import itertools as it

rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king")
suit_string = ("clubs","diamonds","hearts","spades")

print 'The cards are:'
for i, card in enumerate(it.product(rank_string, suit_string)):
    print i, '{0[1]} of {0[0]}'.format(card)

他のヒント

これを見てください

    cards.append(card_string)

print "The cards are:"
for i in range(52):              #how to make this for loop work??
    print i, card_string[i]

なぜ印刷するのか card_string[i]?

どうしたの cards[i]?

ranks = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king")
suits = ("clubs","diamonds","hearts","spades")

答えはエレガントなワンライナーです:

cards = [rank+' of '+suit for suit in suits for rank in ranks]

for i,card in enumerate(cards):
    print i, card

結果:

0 ace of clubs
1 two of clubs
...
50 queen of spades
51 king of spades
def define_cards():
    rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king")
    suit_string = ("clubs","diamonds","hearts","spades")
    cards = []
    n = 0
    for suit in suit_string:
        for rank in rank_string:
            print '%s %s of %s' % (n,rank,suit)
            n+=1

define_cards()

イテレーターを使用してみませんか:

def define_cards():
    rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king")
    suit_string = ("clubs","diamonds","hearts","spades")
    for suit in suit_string:      # you can obtain the items of the iterate list directly, no need of rank access
        for rank in rank_string:
            card_string = rank + " of " + suit
            yield card_string

print "The cards are:"
cards_iterator = define_cards()
for i, card in enumerate(cards_iterator):   # use the iterator power ;)
    print i, card
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top