gpt4 book ai didi

python - “int”对象不可迭代

转载 作者:行者123 更新时间:2023-11-28 20:43:56 25 4
gpt4 key购买 nike

我一直在尝试使用函数获取将其值从字符串更改为 int 的列表的总和

player_hand = [] 

def card_type(player_hand):
card_value = 0
if player_hand[0] == 'A':
card_value = 11
if player_hand[0] == 'J':
card_value = 10
if player_hand[0] == 'Q':
card_value = 10
if player_hand[0] == 'K':
card_value = 10

if player_hand[0] == '2':
card_value = 2
if player_hand[0] == '3':
card_value = 3
if player_hand[0] == '4':
card_value = 4
if player_hand[0] == '5':
card_value = 5
if player_hand[0] == '6':
card_value = 6
if player_hand[0] == '7':
card_value = 7
if player_hand[0] == '8':
card_value = 8
if player_hand[0] == '9':
card_value = 9
if player_hand[0] == '1':
card_value = 10

def player_hit(card_deck):
rando = random.randint(0,len(card_deck)-1)
player_hand.append(card_deck[rando])
card_deck.remove(card_deck[rando])

然后尝试使用

找到玩家列表的总和
card_total = 0

print('Player was handed:')
for i in range(2):
print(player_hit(card_deck))

for i in len(player_hand)-1:
print('\n',sum(card_type(player_hand[i])))

但是我得到一个错误

for i in len(player_hand)-1:
TypeError: 'int' object is not iterable

我不明白问题出在哪里,因为我已经获取了值并将它们转换为 int,并检查了列表索引范围。请帮忙

最佳答案

len(player_hand) - 1 只是一个整数,但您编写的代码会尝试对其进行循环。您需要一个可迭代对象来执行 for 循环。试试这个:

 for i in range(len(player_hand)):
# do your thing here

另一种方法是直接迭代 player_hand,因为它是可迭代的,就像这样:

 for card in player_hand:
print('\n', card_type(card))

关于python - “int”对象不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28017142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com