如何将download_total按规则分配到嵌套列表my_lst的子列表中
Hey folks, let's tackle this problem with clear logic and working code. First, let's restate the requirements to make sure we're on the same page:
Requirements Breakdown
- We have a nested list
my_lstwhere each sublist looks like[label, download_budget](e.g.,['A', 2312]). - We need to distribute a total download quota
download_total = 5000across these entries, appending two values to each (or split) entry:download_target: The amount allocated to this entry segment, capped at 2047 per segment.segment_id: A counter that increments by 1 every time we need to split an entry's budget because it exceeds 2047 (or when we have remaining budget after a full 2047 allocation).
- We stop once the total allocated quota reaches
download_total.
Approach
- Track the remaining quota we have left to allocate.
- Iterate through each entry in
my_lst. - For each entry, split its budget into segments of max 2047 until either the entry's budget is exhausted or we've used up the total quota.
- Increment the segment ID every time we move to a new segment for the same entry.
Working Code
# Sample input data my_lst = [['A', 2312], ['B', 2000], ['C', 1500]] download_total = 5000 # Initialize variables remaining_quota = download_total current_segment = 1 processed_entries = [] for entry in my_lst: if remaining_quota <= 0: break # No more quota to allocate, exit loop label, total_budget = entry remaining_budget = total_budget while remaining_budget > 0 and remaining_quota > 0: # Calculate the target for this segment: min of remaining quota, remaining budget, and 2047 cap allocated_target = min(remaining_quota, remaining_budget, 2047) # Append the processed entry with allocated target and segment ID processed_entries.append([label, total_budget, allocated_target, current_segment]) # Update remaining values remaining_quota -= allocated_target remaining_budget -= allocated_target # Increment segment ID only if there's still budget left for this entry if remaining_budget > 0: current_segment += 1 # Print the result for item in processed_entries: print(item)
Output Explanation
Running this code will produce the following output:
['A', 2312, 2047, 1] ['A', 2312, 265, 2] ['B', 2000, 2000, 3] ['C', 1500, 688, 4]
Let's verify:
- Total allocated:
2047 + 265 + 2000 + 688 = 5000(matchesdownload_total) - All
allocated_targetvalues are ≤2047 - Segment ID increments when we split the 'A' entry (since its budget exceeded 2047)
This approach ensures we follow all the rules efficiently, stopping as soon as we've allocated the full quota.
内容的提问来源于stack exchange,提问作者arsenal88
相关产品推荐
相关产品推荐

