python - 有没有办法通过迭代创建变量?
问题描述
因此,我尝试为在线二十一点程序编写代码,但在编程命中时遇到了麻烦,因为我需要使用从列表中随机抽取的多达 11 个变量进行计算。现在,我对该部分的代码是:
while user_card_total_one <= 21:
user_move = input("Would you like to stand or hit? ")
user_move = user_move.lower()
if user_move == "stand":
break
elif user_move == "hit":
user_card_three = random.choice(deck)
deck.remove(user_card_three)
a_or_an_one = " a "
if user_card_three == 8 or user_card_three == "Ace":
a_or_an_one = " an "
print("You were dealt" + a_or_an_one + str(user_card_three) + ".")
if type(user_card_three) == str and user_card_one != "Ace":
user_card_one = 10
if user_card_three == "Ace":
user_card_total_one = user_card_total_one + 1
user_card_total_two = user_card_total_two + 11
if user_card_total_two > 21:
print("Your card total is " + str(user_card_total_one) + ".")
else:
print("Your card total is " + str(user_card_total_one) + " or " + str(user_card_total_two) + ".")
else:
user_card_total_one = user_card_total_one + user_card_three
user_card_total_two = user_card_total_two + user_card_three
print("Your card total is " + str(user_card_total_one) + ".")
if user_card_total_one > 21:
print("Unfortunately, you busted and lost.")
print("The dealer has collected your bet.")
bust = True
break
else:
print("Sorry, thats not a valid input, please try again.")
现在,我可以多次编写这段代码,以便说明用户决定做什么,但代码中唯一的变化是变量名。我想知道是否有某种方法可以使这个for
循环成为变量name
依赖于 i 的循环?我尝试使用字典:
card = {
1: "Ace",
2: "King",
3: 2
}
card = 1
for i in range (10):
print(card[card])
card = card+1
但这似乎没有帮助。这是我只需要蛮力的东西,还是我想念的更简单的方法?
编辑:对不起,我在第二部分使用了错误的代码,现在更新了
解决方案
我相信您想在字典中的键命名中使用迭代器?这看起来怎么样?
length=10
cardDict=dict()
for i in range(length):
objectname = "Card "+str(i)
cardDict[objectname]="number "+str(i)
print (cardDict)