Python: 如何将for循环的结果合并为一个输出?

Python: How to combine the results of for loop into one output?

numbers = [1, 2, 3]

for number in numbers:
   number = number * 2 

#For the output I will get:
2
4
6

如何修改我的代码以便在不使用 print 语句的情况下合并结果(例如 [2, 4, 6])?

使用列表理解:

[num*2 for num in numbers]

>>> numbers = [1, 2, 3]
>>> [num*2 for num in numbers]
[2, 4, 6]
>>> 

创建新的列表类型变量result并通过列表append()方法向其中添加值。

演示:

>>> numbers = [1, 2, 3]
>>> result = []
>>> for i in numbers:
...   result.append(i*2)
... 
>>> result
[2, 4, 6]
>>> 

如果您想将结果收集到一个列表中,您只需创建一个列表,然后 append 将每个结果添加到其中:

numbers = [1, 2, 3]
doubles = []
for number in numbers:
    double = number * 2 
    doubles.append(double)

... 或者,更简洁地,对列表理解做同样的事情:

numbers = [1, 2, 3]
doubles = [number * 2 for number in numbers]