'int'对象不可迭代 [英] 'int' object not iterable

查看:169
本文介绍了'int'对象不可迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i've been trying to get the sum of list that changed its values from a string to int using a function

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并检查了列表索引范围.请帮助

i don't understand what the problem is because ive taken the values and converted them into int's already as well as checked the list index range. Please help

推荐答案

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

len(player_hand) - 1 is just an integer, but the code you've written tries to loop over it. You need an iterable object to perform a for loop. Try this:

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

另一种选择是直接在player_hand上进行迭代,因为它是可迭代的,就像这样:

An alternative would be iterating directly over player_hand since it is iterable, just like this:

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

这篇关于'int'对象不可迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆