python - 当我想要一个列表时,为什么我得到一个元组作为返回值?
问题描述
对于我的第一个项目,我正在尝试制作二十一点。我希望能够在列表中返回user_cards
andcomputer_cards
然后在下一个函数中使用它们来检查二十一点(21)。出于某种原因,我得到这个错误代码,因为它把这些值作为一个元组返回,我想?
Traceback (most recent call last):
File "main.py", line 1, in <module>
from black_jack_game import *
File "/home/runner/blackjack-start/black_jack_game.py", line 52, in <module>
calculate_score(dealt_cards)
File "/home/runner/blackjack-start/black_jack_game.py", line 43, in calculate_score
if user_card[item] == 11:
TypeError: list indices must be integers or slices, not tuple
代码 :
import random
# dealing the cards to the user
def deal_card():
cards = [11,2,3,4,5,6,7,8,9,10,10,10,10] * 4 # a full 52 card deck
user_cards = []
computer_cards = []
#getting a random card
for i in range(0,3):
user_cards.append(random.choice(cards))
computer_cards.append(random.choice(cards))
# this will remove the cards that have ben used
for i in user_cards:
if i in cards:
cards.remove(i)
for i in computer_cards:
if i in cards:
cards.remove(i)
# this returns a list
return [user_cards,computer_cards]
dealt_cards = deal_card()
# adding the score up of those cards
def calculate_score(func):
#spliting the list that returned from the last function
user_card = dealt_cards[0]
computer_card = dealt_cards[1]
#getting the sum
user_card_sum = sum(user_card)
computer_card_sum = sum(computer_card)
# check for an 11 (ace)
# over 21, remove the 11 and replace it with a 1
for item in enumerate(user_card):
if user_card[item] == 11:
user_card[item] = 1
# a hand with only 2 cards: ace + 10) and return 0
if user_card_sum == 21 | computer_card_sum == 21:
return 0
print(user_card,user_card_sum)
calculate_score(dealt_cards)
解决方案
您在循环中使用enumerate()
了方法 for
enumerate()
方法将计数器添加到可迭代对象并返回它。返回的对象是一个枚举对象。基本上它(index, element)
为数组中的每个元素返回对。
因此,您可以尝试通过将代码更改为:
for index, item in enumerate(user_card):
if user_card[index] == 11:
user_card[index] = 1
或者简单地说:
for idx in range(len(user_card)):
if user_card[idx] == 11:
user_card[idx] = 1
推荐阅读
- c++ - 使用 Matlab Coder 将 Matlab 代码转换为 C++ - 单元问题
- c# - 在 Azure DevOps 上生成错误但不是本地错误
- mysql - MySQL远程连接需要超过3分钟才能显示结果
- java - 如何将 @SuppressWarning("unchecked") 用于特定的代码行而不是方法级别
- python - matplotlib 中不需要的白色列 - 如何删除?
- java - 使用 Spring Security 的仅用户名身份验证
- docker - 从 docker-compose.yml 配置搬运工(-ce)
- c# - 我如何将数据表从 .net core 5.0 web api 作为 json 传递到 angular 前端?
- ssis - 无法在 WinSCP 中从 FTP 检索文件 - 错误消息
- node.js - Mongoose updateMany by id 使用 Node