如何单行提取二维列表首列及索引?如何合并两个列表推导式为单行?
Hey there! Let's make this code cleaner and more efficient—your current approach works, but we can cut down on redundancy and avoid traversing the array twice.
The Optimal Solution: Use enumerate + zip
Instead of generating indices with range(len(array)) and then looping again to grab the first column, we can use enumerate to get both the index and each row in a single pass. Then we'll unpack the results into your two lists using zip:
# If you're okay with tuples (no extra conversion needed) x, y = zip(*((idx, row[0]) for idx, row in enumerate(array))) # If you specifically need lists instead of tuples x, y = map(list, zip(*((idx, row[0]) for idx, row in enumerate(array))))
Why This Works
enumerate(array)iterates through your 2D list and returns pairs of(index, row)—so we only loop througharrayonce, unlike your original code which loops twice (once for indices, once for the first column).- The generator expression
((idx, row[0]) for idx, row in enumerate(array))creates pairs of index + first element of each row. zip(*...)unpacks these pairs into two separate sequences: one with all indices, one with all first-column values.map(list, ...)converts the resulting tuples fromzipinto lists if you need mutable lists instead of immutable tuples.
Example Usage
Let's test this with a sample array:
array = [[10, 20, 30], [40, 50, 60], [70, 80, 90]] x, y = map(list, zip(*((idx, row[0]) for idx, row in enumerate(array)))) print(x) # Output: [0, 1, 2] print(y) # Output: [10, 40, 70]
A Slightly Shorter (But Less Efficient) Alternative
If you don't mind traversing the array twice but still want cleaner code than your original, you can replace range(len(array)) with enumerate:
x, y = [idx for idx, _ in enumerate(array)], [row[0] for row in array]
This is shorter than your original line, but keep in mind it still loops through array two times—so the first solution is better for performance, especially with large arrays.
内容的提问来源于stack exchange,提问作者Vural Erdogan

