كيفية استخدام لحلقة لطباعة بطاقات?
-
29-10-2019 - |
سؤال
لقد تم إعداد جميع البطاقات الـ 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
ومع ذلك ، إذا كنت تبحث عن حل "أكثر بيثونيك" ، جرب هذا:
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)
نصائح أخرى
إلقاء نظرة على هذا فقط giveacodicetagpre.
لماذا طباعة card_string[i]
؟
ما هو الخطأ في cards[i]
؟
giveacodicetagpre.
الإجابة هو بطانة أنيقة: giveacodicetagpre.
النتيجة: giveacodicetagpre.
Genacodicetagpre
لماذا لا تستخدم مكررًا: Genacodicetagpre
لا تنتمي إلى StackOverflow