一句话演示:

  1. >>> [x * x for x in range(1, 11)]
  2. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

条件筛选

  1. >>> [x * x for x in range(1, 11) if x % 2 == 0]
  2. [4, 16, 36, 64, 100]

两层循环

  1. >>> [m + n for m in 'ABC' for n in 'XYZ']
  2. ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

列出当前目录下的所有文件和目录名:

  1. >>> import os # 导入os模块,模块的概念后面讲到
  2. >>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
  3. ['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']


练习

将列表中的字符串改成首字母大写:

  1. L1 = ['Hello', 'World', 18, 'Apple', None]
  2. L2 = [ x.lower() if isinstance(x,str) else x for x in L1 ]
  3. print(L2)