如何用列表推导式替代for循环实现列表创建与元素分组?
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) // ngives the exact number of rows (since you confirmed len(values) is divisible by n)- For each
iin that range, we take a slice ofvaluesstarting ati*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

