Python嵌套列表运算求助:扁平化操作后需保留原分组结构
Hey there! Let's tackle this problem—you want to divide every element in your nested list by 2 while keeping the original grouping structure. Here are two straightforward approaches to get exactly the result you're looking for.
1. Nested List Comprehension (Most Pythonic & Concise)
This method directly iterates over each sublist and its elements, applying the division operation without needing to flatten and reconstruct the list. It's clean and efficient for this use case.
list_1 = [[1,3,0,1], [1,1,0,2,3,0,4], [2,1,2,2,3,4]] list_2 = [[x / 2 for x in sublist] for sublist in list_1] print(list_2) # Output: [[0.5, 1.5, 0.0, 0.5], [0.5, 0.5, 0.0, 1.0, 1.5, 0.0, 2.0], [1.0, 0.5, 1.0, 1.0, 1.5, 2.0]]
How it works:
- The outer comprehension loops through each sublist in
list_1. - The inner comprehension loops through each element
xin the current sublist, dividing it by 2. - The result is a new nested list with the same structure as the original, but every element modified as needed.
2. Flatten → Process → Reconstruct (As per your described workflow)
If you specifically want to follow the flatten-then-restore approach (maybe for more complex operations that require the full flattened list), here's how to implement it:
list_1 = [[1,3,0,1], [1,1,0,2,3,0,4], [2,1,2,2,3,4]] # Step 1: Track the length of each sublist to reconstruct later sublist_lengths = [len(sublist) for sublist in list_1] # Step 2: Flatten the nested list into a single list flattened = [element for sublist in list_1 for element in sublist] # Step 3: Perform the division operation on every element processed_flattened = [x / 2 for x in flattened] # Step 4: Reconstruct the original nested structure list_2 = [] current_index = 0 for length in sublist_lengths: # Slice the processed list to get the sublist of the correct length list_2.append(processed_flattened[current_index:current_index + length]) current_index += length print(list_2) # Output matches the expected result
How it works:
- We first save the length of each sublist so we know how to split the processed flattened list back into groups.
- Flatten the list to apply the operation to all elements uniformly.
- After processing, we use the saved lengths to slice the flattened list back into the original nested structure.
Both methods will give you the exact list_2 you're expecting. The nested list comprehension is ideal for this simple element-wise operation, while the flatten-reconstruct approach is useful if you need to perform more complex processing on the entire dataset first.
内容的提问来源于stack exchange,提问作者GAG

