有什么办法可以使代码更紧凑?

时间:2019-04-04 22:28:45

标签: python python-3.x dry

我正在用python开发API以收集信息,以供以后在学习机中使用。我已经编写了一个“草稿”代码,但是有没有什么有效的方法可以使该代码尽可能紧凑呢?

import requests

api_dir = 'https://fortnite-public-api.theapinetwork.com/prod09/users/id?username='

tuid = input('To see stats enter an user :')

dir1 = api_dir + tuid

data_id = requests.get(dir1).json()

data_arreg = data_id['uid']

api2_dir = 'https://fortnite-public-api.theapinetwork.com/prod09/users/public/br_stats_v2?user_id='

dir2 = api2_dir + data_arreg

data_stats = requests.get(dir2).json()

statskills = data_stats['overallData']['defaultModes']['kills']

statsmatch = data_stats['overallData']['defaultModes']['matchesplayed']

print('Number of total kills is {}.'.format(statskills))

print('Has a total of {} matches played.'.format(statsmatch))

我正在开发此代码,作为学习API并使用其中的信息的一种方式。 (这就是我使用Fortnite API的原因,因为它类似于我稍后要开发的个人项目)

1 个答案:

答案 0 :(得分:0)

您似乎并没有真正重复自己。您可以使用字符串格式通过删除变量并将变量直接放入其中来缩短代码:

import requests

tuid = input('To see stats enter an user :')

data_id = requests.get('https://fortnite-public-api.theapinetwork.com/prod09/users/id?username={}'.format(tuid)).json()

data_stats = requests.get('https://fortnite-public-api.theapinetwork.com/prod09/users/public/br_stats_v2?user_id={}'.format(data_id['uid'])).json()

print('Number of total kills is {}.\nHas a total of {} matches played.'.format(data_stats['overallData']['defaultModes']['kills'], data_stats['overallData']['defaultModes']['matchesplayed']))

这会使每一行都有点长...