python - 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?
解决方案
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}')
推荐阅读
- javascript - 如何计算没有假期的开始日期和结束日期之间的差异?JavaScript
- jquery - 使用 keyup 从 XML 中获取值
- flutter - 颤动中的WebEntryPoint
- html - 在jQuery中使用这个带有html符号的文本方法来查找里面有符号的td
- javascript - 在 R/Shiny 中获取本地文件数据
- django - django 3 中的 /accounts/login 没有传递额外的上下文
- javascript - 弹出窗口不会从内容接收更新的数据
- c# - 如何在 C# 中的 DataGridView 中搜索更多列
- docker - 如何将现有图像作为容器启动,使其在后台运行
- python - 将数据附加到 csv 的问题