Python按索引将列表拆分为n个子列表的高效实现方法
If I understand your requirement correctly, you want to distribute elements from the original list into n sublists in a round-robin fashion: first element to sublist 1, second to sublist 2, ..., nth to sublist n, then n+1th back to sublist 1, and so on.
Here are two efficient ways to achieve this in Python:
Method 1: Concise Slicing (Most Efficient)
Python's list slicing is optimized and perfect for this scenario. Using lst[i::n] picks elements starting at index i with a step of n, which exactly matches the distribution pattern you need:
def split_sequential(lst, n): return [lst[i::n] for i in range(n)]
Example Usage:
l = [1,1,1,2,2,2,3,3,3] n = 3 print(split_sequential(l, n)) # Output: [[1,2,3],[1,2,3],[1,2,3]]
This works even if the original list's length isn't a multiple of n. For example, if l = [1,2,3,4,5] and n=2, you'll get [[1,3,5], [2,4]] which follows the same round-robin logic.
Method 2: Intuitive Loop Approach
If you prefer a more explicit implementation that makes the distribution logic clear, you can initialize n empty sublists and iterate through the original list, appending each element to the corresponding sublist using modulo arithmetic:
def split_sequential(lst, n): result = [[] for _ in range(n)] for idx, item in enumerate(lst): result[idx % n].append(item) return result
Example Usage:
Same as above, this will produce the exact output you're looking for. The idx % n calculation ensures we cycle through the sublist indices as we process each element.
Both methods are efficient, but the slicing approach is generally faster for large lists since it leverages Python's built-in optimized operations.
内容的提问来源于stack exchange,提问作者Ortal Turgeman

