有没有办法让这段代码更紧凑?

Is there any way to make this code more compact?

我正在 python 中开发一个 API 来收集信息,以便稍后在学习机中使用。我已经编写了一个 "draft" 代码,但是有没有什么有效的方法可以使此代码尽可能紧凑?

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 和使用其中信息的一种方式。 (这就是为什么我使用了堡垒之夜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']))

虽然每行有点长...