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

如何以最简洁地道的方式向数组列表添加元素?能否完全移除代码中的循环?

Hey there! Let's figure out how to generate your target list [[0, -1], [1, 0], [2, 1]] without writing any explicit loops in your code. Here are a couple of clean, loop-free approaches in Python:

Approach 1: Using zip() + map()

This method leverages built-in functions to handle pairing and conversion without manual loop logic:

result = list(map(list, zip(range(3), range(-1, 2))))
  • range(3) generates the sequence 0, 1, 2
  • range(-1, 2) generates -1, 0, 1
  • zip() pairs corresponding elements from the two ranges into tuples
  • map(list, ...) converts each tuple to a list
  • Wrapping the whole thing in list() gives you the final nested list.

Approach 2: List Comprehension (Implicit Loop)

If you’re okay with Python’s implicit loop syntax sugar, this is an even more concise and Pythonic option:

result = [[i, i-1] for i in range(3)]

This directly constructs each sublist by calculating i and i-1 for every value in range(3)—no manual for/while loops in your code at all.

Both approaches will output exactly the list you need, with zero hand-written loops.

内容的提问来源于stack exchange,提问作者John Difool

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:10:18