You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何单行提取二维列表首列及索引?如何合并两个列表推导式为单行?

Clean Way to Extract Indices and First Column of a 2D List in One Line

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 through array once, 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 from zip into 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:17:17