如何在Python 3中合并n个等长列表并按索引分组?
Got it, let's figure out how to adjust your function to handle any number of lists while keeping the length validation you had in your original three-list function.
First, let's break down why your initial assemble_lists didn't work:
return [list[::] for list in list_of_lists]
This code just creates a copy of each input list and wraps them in another list—so you end up with the original lists nested, not merged by their index positions.
Correct Implementation
We can use Python's built-in zip() function to "transpose" the list of lists, which exactly does the merging you need. Plus, we'll keep your length check to avoid silent data loss.
Here are two flexible versions depending on how you want to pass your lists:
Option 1: Accept multiple list arguments (great for direct calls)
def assemble_lists(*lists): # Handle empty input case if not lists: return [] # Check if all lists have the same length base_length = len(lists[0]) for lst in lists[1:]: if len(lst) != base_length: raise Exception("Some elements have been lost, critical error.") # Zip the lists and convert each tuple to a list return [list(item) for item in zip(*lists)]
Option 2: Accept a single list of lists (matches your initial attempt's parameter style)
def assemble_lists(list_of_lists): # Handle empty input case if not list_of_lists: return [] # Check if all lists have the same length base_length = len(list_of_lists[0]) for lst in list_of_lists[1:]: if len(lst) != base_length: raise Exception("Some elements have been lost, critical error.") # Zip the lists and convert each tuple to a list return [list(item) for item in zip(*list_of_lists)]
How It Works
- Length Validation: We first check that every list has the same length as the first one—just like your original function, this prevents silent data loss if lists are mismatched.
zip(*lists): The*unpacks the input lists into separate arguments forzip(), which then pairs up elements at the same index across all lists. For your example, this gives tuples like('a', 1, '!').- Convert to Lists: Since
zip()returns tuples, we wrap each result inlist()to get the sub-lists you want in the output.
Test It Out
Using your sample input:
l1 = ["a", "b", "c"] l2 = [1, 2, 3] l3 = ["!", "@", "#"] # For Option 1 print(assemble_lists(l1, l2, l3)) # Output: [['a', 1, '!'], ['b', 2, '@'], ['c', 3, '#']] # For Option 2 print(assemble_lists([l1, l2, l3])) # Same output
This matches your desired output perfectly, and works for any number of equal-length lists.
内容的提问来源于stack exchange,提问作者Ryan Bircham

