pyhotn3入门基础-10 列表生成式

来源:互联网 发布:php在线格式化工具 编辑:程序博客网 时间:2024/05/16 08:18

list(range(1,11))

>>> list(range(1, 11))[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

生成[1x1, 2x2, 3x3, ..., 10x10]

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

for循环后的判断

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

用for双重循环 for for

>>> [m + n for m in 'ABC' for n in 'abc']['Aa', 'Ab', 'Ac', 'Ba', 'Bb', 'Bc', 'Ca', 'Cb', 'Cc']

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

>>> import os>>> [d for d in os.listdir('.')]['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python35.dll', 'pythonw.exe', 'README.txt', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']

for循环可以同时有2个以上的变量,如dict的items()可以同时迭代key和value

>>> d = {'key1':'a', 'key2': 'b', 'key3': 'cc'}>>> for k , v in d.items():print(k, '=', v)key2 = bkey1 = akey3 = cc

>>> [k + '=' + v for k, v in d.items()]['key2=b', 'key1=a', 'key3=cc']


把大写字母变成小写字母

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


判断是否是字符

>>> x = 123>>> isinstance(x,str)False






















原创粉丝点击