numbers = [1, 2, 3]
for number in numbers:
number = number * 2
#For the output I will get:
2
4
6
如何在不使用print语句的情况下修改我的代码以便结果(例如[2,4,6])?
答案 0 :(得分:5)
使用列表理解:
[num*2 for num in numbers]
>>> numbers = [1, 2, 3]
>>> [num*2 for num in numbers]
[2, 4, 6]
>>>
答案 1 :(得分:1)
创建新的列表类型变量result
,并按列表append()
方法将值添加到其中。
演示:
>>> numbers = [1, 2, 3]
>>> result = []
>>> for i in numbers:
... result.append(i*2)
...
>>> result
[2, 4, 6]
>>>
答案 2 :(得分:0)
如果您想将结果收集到列表中,只需创建一个列表并在其中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]