压缩简单的功能

时间:2014-06-02 00:28:46

标签: python-2.7

当我与匿名函数斗争时, 我怎样才能将下面的代码信息改成一行?

list1 = []
for i in range(some_number):
    list1.append(i * 100 + 50)

1 个答案:

答案 0 :(得分:1)

使用列表理解:

list1 = [i*100 + 50 for i in range(some_number)]

运行如下:

>>> list1 = [i*100 + 50 for i in range(10)]
>>> list1
[50, 150, 250, 350, 450, 550, 650, 750, 850, 950]
>>> 

与以下内容相同:

>>> list1 = []
>>> for i in range(10):
...     list1.append(i*100 + 50)
... 
>>> list1
[50, 150, 250, 350, 450, 550, 650, 750, 850, 950]
>>>