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

如何用列表推导式替代for循环实现列表创建与元素分组?

Using List Comprehensions Instead of For Loops for List Creation

Absolutely—list comprehensions are ideal for replacing loops that exist solely to build a list. They’re more concise, readable (once you’re familiar with them), and often perform better than equivalent for loops with append() calls.

General Example

If you have a loop like this:

my_list = []
for x in range(10):
    my_list.append(x * 2)

You can rewrite it in one line with a list comprehension:

my_list = [x * 2 for x in range(10)]

Your Specific Grouping Problem

First, let’s fix a small bug in your original loop: right now, you’re using values[i:i+9], which creates overlapping slices once i is greater than 0 (e.g., i=1 gives elements 1-10 instead of the second full row of 9 elements). You should use n dynamically and calculate slice bounds as i*n to (i+1)*n instead.

Here’s the corrected for loop:

def group(values, n):
    grouped_values = []
    for i in range(len(values) // n):
        grouped_values.append(values[i*n : (i+1)*n])
    return grouped_values

And here’s the equivalent list comprehension version—cleaner and more compact:

def group(values, n):
    return [values[i*n : (i+1)*n] for i in range(len(values) // n)]

This works because:

  • len(values) // n gives the exact number of rows (since you confirmed len(values) is divisible by n)
  • For each i in that range, we take a slice of values starting at i*n (the start of the row) and ending at (i+1)*n (the end of the row)
  • The list comprehension collects all these slices into the final grouped list, which matches your expected output perfectly.

Testing this with your values and n=9 will produce exactly the grouped_values you provided.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:40:17