Day9 python高级特性-- 列表生成式 List Comprehensions

Python内置的非常简单却强大的可以用来创建list的生成式。
    私理解为,就是for循环出来的结果搞成个list~~~~
   
要生成顺序增量list可以使用list(range(x,y))来进行,如:
        >>> list(range(1,11))
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        >>> list(range(-12,-1))
        [-12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2]
        >>> list(range(11,1))
        []
        >>> list(range(-1,-12))
        []
       
但是要生成[1x1, 2x2, 3x3, 4x4, ..., 10x10]怎么做呢?可以用for循环:
        >>> L = []
        >>> for i in range(1,11):       #为什么是11?想想。
        ...     L.append(i * i)
        ...
        >>> L
        [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
       
也可以用列表生成式,更容易的实现:
        >>> [x * x for x in range(1,11)]
        [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
       
列表生成式:
    要生成的元素放到前面,后面跟for循环,就可以轻松的创建出list了。
   
   1.  for循环后可以加上if判断,如计算奇数的平方
        >>> [ x * x for x in range(1,11) if x % 2 == 1]
        [1, 9, 25, 49, 81]
   2.  也可以对for循环做多层嵌套,如两层:
        >>> [ m + n for m in 'ABCD' for n in 'abcdef' ]
        ['Aa', 'Ab', 'Ac', 'Ad', 'Ae', 'Af', 'Ba', 'Bb', 'Bc', 'Bd', 'Be', 'Bf', 'Ca', 'Cb', 'Cc', 'Cd', 'Ce', 'Cf', 'Da', 'Db', 'Dc', 'Dd', 'De', 'Df']
        三层和三层以上用的很少。
    3.  for循环可以同时使用两个以及更多个变量
        >>> a = { 'a': 'A', 'b': 'B', 'c': 'C' }
        >>> [ Alpha + '=' + Num for Alpha, Num in a.items() ]
        ['c=C', 'b=B', 'a=A']
       
        发现一个问题,如果有一个变量为int类型,则会出问题:
            >>> a = { 'a': 1, 'b': 2, 'c': 3 }
            >>> [ A + '=' + N for A, N in a.items() ]
            Traceback (most recent call last):
              File "<stdin>", line 1, in <module>
              File "<stdin>", line 1, in <listcomp>
            TypeError: Can't convert 'int' object to str implicitly
        这样就好了:
            >>> [ A + '=' + str(N)  for A , N in a.items()]
            ['c=3', 'b=2', 'a=1']
           
练习:
    1.把list中所有字符串变成小写
        >>> a = ['ABC', 'DEF', 'GHI']
        >>> [ i.lower() for i in a]
        ['abc', 'def', 'ghi']
    2.把list中的单词变成首字母大写
        >>> a = ['abc', 'def', 'ghi']
        >>> [ i[0].upper() + i[1:].lower() for i in a]
        ['Abc', 'Def', 'Ghi']
    3.前两个练习中的list如果出现数字,如何保证依然正确处理。
        #引入: 可以用isinstance()函数来判断是否为str
        >>> a = ['ABC', 'DEF', 'GHI', None, 123, 555]
        >>> [ i.lower() for i in a if isinstance(i, str) == True ]
        ['abc', 'def', 'ghi']
        >>> a = ['abc', 'def', 'ghi', None, 123, 'ABC']
        >>> [ i[0].upper() + i[1:].lower() for i in a if  isinstance(i, str)]
        ['Abc', 'Def', 'Ghi', 'Abc']    
       
    4.在3的基础上,能让非字符串也显示出来么?
        >>> a = ['abc', 'def', 'ghi', None, 123, 'ABC']
        >>> [ i[0].upper() + i[1:].lower() if isinstance(i, str) else i for i in a ]
        ['Abc', 'Def', 'Ghi', None, 123, 'Abc']   
        #这块的用法和老廖的课程上有些不同,理解理解。
        #先判断是否满足条件,满足则转换,不满足则不变。
        #而之前的是,先转换,再根据条件筛选结果?应该是这样的。
   
扩展:使用os模块的listdir,列出操作系统的文件和目录
        >>> import os
        >>> os.listdir('/')
        ['bin', 'boot', 'dev', 'etc', 'home', 'init', 'lib', 'lib64', 'media', 'mnt', 'opt', 'proc', 'root', 'run', 'sbin', 'srv', 'sys', 'tmp', 'usr', 'var']
       
        >>> a = [ 'ls /' + n for n in os.listdir('/') ]
        >>> for i in range(0,len(a)):
        ...     print(a[i])
        ...
        ls /bin
        ls /boot
        ls /dev
        ls /etc
        ls /home
        ls /init
        ls /lib
        ls /lib64
        ls /media
        ls /mnt
        ls /opt
        ls /proc
        ls /root
        ls /run
        ls /sbin
        ls /srv
        ls /sys
        ls /tmp
        ls /usr
        ls /var           
         #shell脚本里最喜欢干的事情~~  

猜你喜欢

转载自www.cnblogs.com/konggg/p/9077468.html