我正在编写代码,以跟踪以字符串列表形式返回的国家所获得的奖牌。格式示例:
"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)
我不确定为什么。 谁能解释我将如何解决此问题? 预先感谢!
答案 0 :(得分:0)
您的代码有几个问题:
这是更新的工作版本
['TPE 0 1 1', 'JPN 0 1 0', 'UKR 0 0 1', 'CHN 0 1 0', 'ITA 1 0 0', 'AUS 0 0 1', 'GBR 0 0 1', 'KOR 3 0 0']
输出
{{1}}
答案 1 :(得分:0)
此行中存在您的问题:
medalTracker = [medalTracker.append(i) for i in allCountries]
当您append
list
时,它会修改list
到位,但返回None
。您会在这里看到更清楚的东西:
allCountries = ['ITA', 'JPN', 'AUS', 'KOR', 'TPE'] # This is essentially the shorter equivalent of your list.
medalTracker = []
def show_medalTracker_detail():
print(f'medalTracker id: {id(medalTracker)}, values: {medalTracker}')
def peek(x):
result = medalTracker.append(x)
show_medalTracker_detail()
return result
运行时:
>>> show_medalTracker_detail()
medalTracker id: 52731616, values: []
>>> medalTracker = [peek(i) for i in allCountries]
medalTracker id: 52731616, values: ['ITA']
medalTracker id: 52731616, values: ['ITA', 'JPN']
medalTracker id: 52731616, values: ['ITA', 'JPN', 'AUS']
medalTracker id: 52731616, values: ['ITA', 'JPN', 'AUS', 'KOR']
medalTracker id: 52731616, values: ['ITA', 'JPN', 'AUS', 'KOR', 'TPE']
>>> show_medalTracker_detail()
medalTracker id: 52736448, values: [None, None, None, None, None]
请注意,列表理解后medalTracker
对象ID和值如何更改?这是因为在列表理解完成循环和附加之后,它还创建了None
的列表,并正在重新分配该列表(一个新对象)以替换您现有的medalTracker
。
解决方案是仅使用medalTracker = list(allCountries)
,或者如果要追加,则使用for循环:
for i in allCountries:
medalTracker.append(i)
答案 2 :(得分:0)
首先,除课外,大写字母通常用于其他用途。继续...
var thread = new Thread(() =>
{
// my code here
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
while(thread.IsAlive)
{
// Wait 100 ms
Thread.Sleep(100);
}
问题出在此行,该行返回None的列表
medalTracker = [medalTracker.append(i) for i in allCountries]
还有其他一些问题,即尝试将某些数据附加到字符串。请看一下这段代码,我认为它将为您提供所需的结果
<class 'list'>: [None, None, None, None, None, None, None, None]