我正在尝试重构一个有大量嵌套for循环的凌乱代码。有没有办法重构这些嵌套循环以使代码更具可读性?
for prof_i in range(num_profiles): # the whole code is repeated for each profile that needs to be generated
Tot_Classes = np.zeros(1440) # initialise an empty daily profile that will be filled with the sum of the hourly profiles of each User instance
for Us in User_list: # iterates for each User instance (i.e. for each user class)
Us.load = np.zeros(1440) # initialise empty load for User instance
for i in range(Us.num_users): # iterates for every single user within a User class. Each single user has its own separate randomisation
rand_daily_pref = 0 if Us.user_preference == 0 else random.randint(1, Us.user_preference)
for App in Us.App_list: # iterates for all the App types in the given User class
# initialises variables for the cycle
tot_time = 0
App.daily_use = np.zeros(1440)
if ((random.uniform(0, 1) > App.occasional_use):
' do something'
'more nested if statements'
while tot_time <= rand_time: #this is the key cycle, which runs for each App until the switch_ons and their duration equals the randomised total time of use of the App
switch_on = App.switch_on()
if 'some more nested statements':
tot_time = tot_time + indexes.size
Us.load = Us.load + App.daily_use # adds the App profile to the User load
Tot_Classes = Tot_Classes + Us.load # adds the User load to the total load of all User classes
Profile.append(Tot_Classes) # appends the total load to the list that will contain all the generated profiles
print('Profile', prof_i + 1, '/', num_profiles, 'completed') # screen update about progress of computation