Skip to content

Commit 00ab345

Browse files
committed
zip,enumerate,list compr
1 parent 38c3c08 commit 00ab345

1 file changed

Lines changed: 34 additions & 3 deletions

File tree

‎124.md‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -264,12 +264,43 @@ python中提供了一个内置函数enumerate,能够实现类似的功能
264264

265265
好的。然后呢?再转化为字符串?留给读者试试。
266266

267-
------
267+
##list解析
268268

269-
[总目录](./index.md)   |   [上节:语句(3)](./123.md)   |   [下节:语句(5)](./125.md)
269+
先看下面的例子,这个例子是想得到1到9的每个整数的平方,并且将结果放在list中打印出来
270+
271+
>>> power2 = []
272+
>>> for i in range(1,10):
273+
... power2.append(i*i)
274+
...
275+
>>> power2
276+
[1, 4, 9, 16, 25, 36, 49, 64, 81]
277+
278+
python有一个非常有意思的功能,就是list解析,就是这样的:
279+
280+
>>> squares = [x**2 for x in range(1,10)]
281+
>>> squares
282+
[1, 4, 9, 16, 25, 36, 49, 64, 81]
283+
284+
看到这个结果,看官还不惊叹吗?这就是python,追求简洁优雅的python!
270285

271-
如果你认为有必要打赏我,请通过支付宝:**qiwsir@126.com**,不胜感激。
286+
其官方文档中有这样一段描述,道出了list解析的真谛:
272287

288+
>List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
273289
290+
这就是python有意思的地方,也是计算机高级语言编程有意思的地方,你只要动脑筋,总能找到惊喜的东西。
274291

292+
其实,不仅仅对数字组成的list,所有的都可以如此操作。请在平复了激动的心之后,默默地看下面的代码,感悟一下list解析的魅力。
293+
294+
>>> mybag = [' glass',' apple','green leaf '] #有的前面有空格,有的后面有空格
295+
>>> [one.strip() for one in mybag] #去掉元素前后的空格
296+
['glass', 'apple', 'green leaf']
297+
298+
上面的问题,都能用list解析来重写。读者不妨试试。
299+
300+
在很多情况下,list解析的执行效率高,代码简洁明了。是实际写程序中经常被用到的。
301+
302+
------
303+
304+
[总目录](./index.md)   |   [上节:语句(3)](./123.md)   |   [下节:语句(5)](./125.md)
275305

306+
如果你认为有必要打赏我,请通过支付宝:**qiwsir@126.com**,不胜感激。

0 commit comments

Comments
 (0)