Python列表生成式

☆首页☆ 论坛 Python学习记录 Python列表生成式

标签: 

正在查看 1 帖子:1-1 (共 1 个帖子)
  • 作者
    帖子
  • #2515
    羊毛客
    管理员

    1.

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

    2.筛选出偶数的平方:

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

    3.使用两个变量来生成list:

    >>> d = {‘x’: ‘A’, ‘y’: ‘B’, ‘z’: ‘C’ }
    >>> [k + ‘=’ + v for k, v in d.items()]
    [‘y=B’, ‘x=A’, ‘z=C’]

    4.两层循环生成全排列:

    >>> [m + n for m in ‘ABC’ for n in ‘XYZ’]
    [‘AX’, ‘AY’, ‘AZ’, ‘BX’, ‘BY’, ‘BZ’, ‘CX’, ‘CY’, ‘CZ’]

    5.把一个list中所有的字符串变成小写:

    >>> L = [‘Hello’, ‘World’, ‘IBM’, ‘Apple’]
    >>> [s.lower() for s in L]
    [‘hello’, ‘world’, ‘ibm’, ‘apple’]

    6.列出当前目录下的所有文件和目录名,可以通过一行代码实现:
    >>> import os # 导入os模块
    >>> [d for d in os.listdir(‘.’)]  # os.listdir可以列出文件和目录
    [‘.emacs.d’, ‘.ssh’, ‘.Trash’, ‘Adlm’, ‘Applications’, ‘Desktop’, ‘Documents’, ‘Downloads’, ‘Library’, ‘Movies’, ‘Music’, ‘Pictures’, ‘Public’, ‘VirtualBox VMs’, ‘Workspace’, ‘XCode’]

    7.for循环可以同时使用两个甚至多个变量,比如dict的items()可以同时迭代key和value:

    >>> d = {‘x’: ‘A’, ‘y’: ‘B’, ‘z’: ‘C’ }
    >>> for k, v in d.items():
    … print(k, ‘=’, v)

    y = B
    x = A
    z = C

正在查看 1 帖子:1-1 (共 1 个帖子)
  • 哎呀,回复话题必需登录。