Python求和整数列表时遭遇TypeError错误求助
问题根源
你的核心错误是**random.choices(cards, k=2)返回的是一个长度为2的列表**,而你用append()把这个列表直接添加到user_hand中,导致user_hand变成了嵌套列表(比如[[11, 5]]),而非扁平的整数列表。这直接引发了两种TypeError:
- 第一种错误:
user_total += i中,i是嵌套列表里的子列表,整数与列表无法执行+=运算 - 第二种错误:
sum(user_hand)或int(user_hand)试图将整个嵌套列表/子列表转为整数,显然不支持
另外你原来的for循环代码还有个小问题:user_total = 0放在循环内部,每次迭代都会重置总和为0,最终只能得到最后一个元素的值,这个逻辑也需要修正。
修复方案
方案1:用extend()替代append()(推荐)
extend()会把传入的列表中的元素逐个添加到目标列表,保持user_hand为扁平的整数列表,直接求和即可:
import random cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] user_hand = [] bot_hand = [] def deal_hand(): # 用extend将选出来的两张牌逐个加入user_hand user_hand.extend(random.choices(cards, k=2)) bot_hand.extend(random.choices(cards, k=2)) # 直接sum扁平列表 user_total = sum(user_hand) print("用户手牌总和:", user_total) deal_hand()
方案2:扁平化嵌套列表(不推荐,仅做补充)
如果一定要保留append(),需要先将嵌套列表转为扁平列表再求和:
import random cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] user_hand = [] bot_hand = [] def deal_hand(): user_hand.append(random.choices(cards, k=2)) bot_hand.append(random.choices(cards, k=2)) # 推导式扁平化嵌套列表 flat_user_hand = [num for sublist in user_hand for num in sublist] user_total = sum(flat_user_hand) print("用户手牌总和:", user_total) deal_hand()
修正原for循环的逻辑(如果不用sum)
如果你想用循环累加,要把user_total = 0放在循环外面:
import random cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] user_hand = [] bot_hand = [] def deal_hand(): user_hand.extend(random.choices(cards, k=2)) bot_hand.extend(random.choices(cards, k=2)) user_total = 0 for num in user_hand: user_total += num print("用户手牌总和:", user_total) deal_hand()
内容的提问来源于stack exchange,提问作者ester
相关产品推荐
相关产品推荐

