Python 3.6.4中高效交替翻转列表成对元素并拆分的最优方案
Hey there! For your batch processing scenario where speed is critical (running thousands of times on Python 3.6.4), here are optimized approaches tailored to your exact requirement:
Optimized Solution 1: List Comprehension with Slicing
This leverages Python's built-in slicing (implemented in C, so extremely fast) and list comprehensions to minimize overhead. The logic is straightforward:
- Split the input tuple into groups of two elements using slicing.
- Alternately reverse every odd-indexed group (0-based) while keeping even-indexed groups intact.
def process_pleated_tuple(input_tuple): # Split into groups of 2 groups = [input_tuple[i:i+2] for i in range(0, len(input_tuple), 2)] # Alternate reverse: keep even-indexed groups, reverse odd-indexed ones return [list(group) if idx % 2 == 0 else list(reversed(group)) for idx, group in enumerate(groups)]
Test with Your Example
pleatedTuple = (0, 1, 3, 2, 4, 5, 7, 6, 8, 9) print(process_pleated_tuple(pleatedTuple)) # Output: [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
You can even condense this into a single list comprehension for a tiny extra speed boost (though readability takes a slight hit):
def process_pleated_tuple_short(input_tuple): return [list(input_tuple[i:i+2]) if i % 4 == 0 else list(reversed(input_tuple[i:i+2])) for i in range(0, len(input_tuple), 2)]
Here, we check the starting index of each group: groups starting at indices 0,4,8 (divisible by 4) stay as-is, while those at 2,6 (remainder 2 when divided by 4) get reversed.
Optimized Solution 2: NumPy for Large Datasets
If you're working with extremely large tuples (10k+ elements), using NumPy's vectorized operations will deliver significant speed gains over pure Python. This avoids Python-level loops entirely:
import numpy as np def process_pleated_tuple_numpy(input_tuple): # Convert tuple to a 2D NumPy array arr = np.array(input_tuple).reshape(-1, 2) # Reverse every odd-indexed row arr[1::2] = arr[1::2, ::-1] # Convert back to a list of lists return arr.tolist()
When to Use This
- Ideal for very large input sizes, where the overhead of converting to a NumPy array is offset by the speed of vectorized operations.
- For smaller tuples, the pure Python list comprehension approach is faster due to lower initialization overhead.
Key Performance Notes
- Slicing is your friend: Python's slicing is implemented in optimized C code, making it far faster than manual element-by-element looping.
- Avoid unnecessary operations: Reversing a 2-element tuple is trivial, but using
reversed()(a built-in function) is still faster than manual swapping in Python. - Input validation: Ensure your input tuples have an even length. If you need to handle odd-length tuples, add a quick check to handle the final single element (e.g., append
[input_tuple[-1]]to the result iflen(input_tuple) % 2 != 0).
内容的提问来源于stack exchange,提问作者Gnarlodious

