首页 > 解决方案 > Why is my program not working as expected?

问题描述

I've got some code for a card game but it's not working as expected.

Code:

from random import choice as c
card_flowers = ['spade', 'heart', 'club', 'diamond']
card_colors = ['black', 'red']
card_roles = ['2', 'A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3']
card = c(card_flowers),c(card_colors),c(card_roles)
p3_cards = card * 18
n = 1
for p3_card in p3_cards:
    print('card ' + str(n) + ':\n' + p3_card + '\n\n', end='')
    n += 1

Output:

card 1:
diamond

card 2:
black

card 3:
3

card 4:
diamond

card 5:
black

card 6:
3

card 7:
diamond

card 8:
black

card 9:
3

card 10:
diamond

card 11:
black

card 12:
3

card 13:
diamond

card 14:
black

card 15:
3

card 16:
diamond

card 17:
black

card 18:
3

card 19:
diamond

card 20:
black

card 21:
3

card 22:
diamond

card 23:
black

card 24:
3

card 25:
diamond

card 26:
black

card 27:
3

card 28:
diamond

card 29:
black

card 30:
3

card 31:
diamond

card 32:
black

card 33:
3

card 34:
diamond

card 35:
black

card 36:
3

card 37:
diamond

card 38:
black

card 39:
3

card 40:
diamond

card 41:
black

card 42:
3

card 43:
diamond

card 44:
black

card 45:
3

card 46:
diamond

card 47:
black

card 48:
3

card 49:
diamond

card 50:
black

card 51:
3

card 52:
diamond

card 53:
black

card 54:
3

I thought it was going to give me 18 cards each with a type of flower, color, and role, but instead it gave me 54 cards each with only 1 kind of element! That's the total number of cards! Plus, the elements were the same for every 3 cards! Anyone explain it to me?

标签: pythonrandom

解决方案


you have created a tuple containing the various elements (flowers, colors, roles,) if you try to print card you can see what is going on, the result will be something like that: ('flower', 'color', 'role', 'flower', 'color', 'role', 'flower', 'color', 'role','...) It will contain always the same 3 element because card was assigned with those 3 different choices, if you want to have different cards every time you have to reassign the variable every time

you must create a 2d list or tuple p3_cards = [[c(card_flowers), c(card_colors), c(card_roles)] for _ in range(18)](I used a list comprehension) and then if you want to iterate p3_cards you should use enumarete to get index and your card.

from random import choice as c


card_flowers = ['spade', 'heart', 'club', 'diamond']
card_colors = ['black', 'red']
card_roles = ['2', 'A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3']

p3_cards = [[c(card_flowers), c(card_colors), c(card_roles)] for _ in range(18)]

for index, card in enumerate(p3_cards):
    print(f'card {index + 1}: \n{card}')

推荐阅读