我正在编写一个代码来跟踪作为字符串列表返回的国家获得的奖牌。格式示例:
"COUNTRY G S B"
以下是我目前的代码:
def generate(results):
"""
return list of strings
based on data in results, a list of strings
"""
# [country_code, gold_count, silver_count, bronze_count ]
allCountries = []
for i in results:
x = i.split()
for country in x:
allCountries.append(country)
allCountries = set(allCountries)
medalTracker = []
medalTracker = [medalTracker.append(i) for i in allCountries]
# medalTracker = list(medalTracker)
for i in medalTracker:
goldCount, silverCount, bronzeCount = 0, 0, 0
Idx = medalTracker.index(i)
medalTracker[Idx].append(goldCount, silverCount, bronzeCount)
for rank in results:
if rank [1] == i:
goldCount += 1
elif rank [2] == i:
silverCount += 1
elif rank[3] == i:
bronzeCount += 1
print(generate(["ITA JPN AUS", "KOR TPE UKR", "KOR KOR GBR", "KOR CHN TPE"]))
应返回:
[ "KOR 3 1 0", "ITA 1 0 0", "TPE 0 1 1", "CHN 0 1 0", "JPN 0 1 0",
"AUS 0 0 1", "GBR 0 0 1", "UKR 0 0 1" ]
我在第20行遇到一个非类型错误:
medalTracker[Idx].append(goldCount, silverCount, bronzeCount)
我不知道为什么。 有人能解释一下我怎么能解决这个问题吗? 提前谢谢!你知道吗
您的问题存在于以下行:
medalTracker = [medalTracker.append(i) for i in allCountries]
当您
append
一个list
时,它会修改list
,但返回None
。你可以更清楚地看到这里发生了什么:运行时:
注意到
medalTracker
对象id和值在理解列表后是如何变化的吗?这是因为在列表理解完成循环和追加之后,它还创建了一个None
列表,并且正在重新分配该列表(一个新对象)以替换现有的medalTracker
。你知道吗解决方案是只使用
medalTracker = list(allCountries)
,或者如果要追加,则使用for循环:首先,一般不赞成用大写字母来表示除类以外的任何事物。继续。。。你知道吗
问题源于这一行,它返回一个None的列表
还有一些其他问题,即尝试将一些数据附加到字符串中。请看一下这个代码,我想它会给你的结果,你正在寻找
你的代码有几个问题:
这是一个更新的工作版本
输出
相关问题 更多 >
编程相关推荐