当然,必须有一种更清洁的方法来做到这一点



我正在构建一个可以显示一些统计数据的机器人。

我从 API 得到这个响应:

"lifeTimeStats": [
{
"key": "Top 5s",
"value": "51"
},
{
"key": "Top 3s",
"value": "69"
},
{
"key": "Top 6s",
"value": "120"
},
{
"key": "Top 10",
"value": "66"
},
{
"key": "Top 12s",
"value": "122"
},
{
"key": "Top 25s",
"value": "161"
},
{
"key": "Score",
"value": "235,568"
},
{
"key": "Matches Played",
"value": "1206"
},
{
"key": "Wins",
"value": "49"
},
{
"key": "Win%",
"value": "4%"
},
{
"key": "Kills",
"value": "1293"
},
{
"key": "K/d",
"value": "1.12"
}
],

这是我格式化此 JSON 的代码:

def __getitem__(self, items):
new_list = []
new_list2 = []
new_list3 = []
new_list4 = []
for item in self.response['lifeTimeStats']:
for obj in item.items():
for object in obj:
new_list.append(object)
for item in new_list[1::2]:
new_list2.append(item)
for item in new_list2[::2]:
new_list3.append(item)
for item in new_list2[1::2]:
new_list4.append(item)
result = dict(zip(new_list3, new_list4))
return result[items]

结果是这样的:

{
'Top 5s': '1793',
'Top 3s': '1230',
'Top 6s': '1443',
'Top 10': '2075',
'Top 12s': '2116',
'Top 25s': '2454',
'Score': '4,198,425',
'Matches Played': '10951',
'Wins': '4077',
'Win%': '37%',
'Kills': '78836',
'K/d': '11.47'
}

我对结果很满意,我只是在想是否有更好的方法来格式化它?更清洁的方式?

我现在正在学习,我要检查是否有人对此有一些想法。

这是我在此之后获取信息的方式:

f = Fortnite('PlayerName')
f['Matches Played']

您可以使用简单的字典理解来迭代结果,即:

def __getitem__(self, item):
return {x["key"]: x["value"] for x in self.response["lifeTimeStats"]}[item]

话虽如此,为什么每当要检索特定项目时都要一直迭代响应?您应该缓存结果,然后仅将其作为普通字典访问。

或者,由于您只对一个密钥感兴趣,因此您可以执行以下操作:

def __getitem__(self, item):
for stat in self.response["lifeTimeStats"]:
if stat["key"] == item:
return stat["value"]

最新更新