Python基础-列表生成式

对列表实现迭代
In [1]: l1 = [1,2,3,4,5]

In [2]: l2 = []

In [3]: for i in l1:
   ...:     l2.append(i**2)
   ...:     

In [4]: print l2
[1, 4, 9, 16, 25]

列表生成式

  • 语法:
    • [expression for iter_var in iterable]
    • [expression for iter_var in iterable if cond_expr]

使用列表生成式完成上面的操作

In [5]: l3 = [ i**2 for i in l1 ]

In [6]: print l3
[1, 4, 9, 16, 25]

列表生成式可直接输出,用时要赋给变量,如下

In [7]: [ i**2 for i in l1 ]    #直接平方
Out[7]: [1, 4, 9, 16, 25]

In [8]: print l1                #打印l1结果没有保存
[1, 2, 3, 4, 5]

for循环后还可以加上if判断,下面算出大于3数字的平方

In [9]: l4 = [ i**2 for i in l1 if i >=3 ]

In [10]: print l4
[9, 16, 25]

列表生成式问题 来自廖雪峰的官方网站

L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = ???
期待输出: ['hello', 'world', 'apple']


In [46]: L1 = ['Hello', 'World', 18, 'Apple', None]

In [47]: L2 = [s for s in L1 if isinstance(s,str)]

In [48]: print (L2)
['Hello', 'World', 'Apple']

列表生成式问题 找出.log结尾的文件

In [51]: import os

In [52]: os.listdir('/var/log')
Out[52]: 
['tallylog',
 'lastlog',
 'wtmp',
 'ppp',
 'audit',
.....略

In [53]: filelist1 = os.listdir('/var/log')

In [54]: str.
str.capitalize  str.format      str.isupper     str.rfind       str.startswith
str.center      str.index       str.join        str.rindex      str.strip
str.count       str.isalnum     str.ljust       str.rjust       str.swapcase
str.decode      str.isalpha     str.lower       str.rpartition  str.title
str.encode      str.isdigit     str.lstrip      str.rsplit      str.translate
str.endswith    str.islower     str.mro         str.rstrip      str.upper
str.expandtabs  str.isspace     str.partition   str.split       str.zfill
str.find        str.istitle     str.replace     str.splitlines  

In [54]: help(str.endswith)
Help on method_descriptor:

endswith(...)
    S.endswith(suffix[, start[, end]]) -> bool
    
    Return True if S ends with the specified suffix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    suffix can also be a tuple of strings to try.


In [55]: s1 = 'boot.log' 

In [56]: s1.endswith('.log')
Out[56]: True

In [57]: s2 = 'btmp'

In [58]: s2.endswith('.log')
Out[58]: False

In [59]: filelist2 = [i for i in filelist1 if i.endswith('.log')]

In [60]: print filelist2
['yum.log', 'boot.log']

posted @ 2017-04-06 16:52  赵东伟  阅读(152)  评论(0)    收藏  举报