我正在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的原因,因为它类似于我后来要开发的个人项目)
看起来你并没有真正重复自己。您可以使用字符串格式来缩短代码,方法是取出变量并直接将它们放入:
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']))
这使得每条线都有点长......