备注:
#列表生成式 #要生成list [1x1, 2x2, 3x3, ..., 10x10] L = [] for i in range(1, 11): i = i * i L.append(i) print (L) #用列表生成式来完成这个任务 [x * x for x in range(1, 11)] #要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来 [x * x * x for x in range(1, 100)] #[4, 16, 36, 64, 100] #偶数的三次方 [x * x * x for x in range(1, 100) if x % 2 ==0] [x * x for x in range(1, 11) if x % 2 ==0] #全排列 [m + n for m in 'xyz' for n in 'abc'] #['xa', 'xb', 'xc', 'ya', 'yb', 'yc', 'za', 'zb', 'zc'] #列表生成式展示文件目录 import os #首先导入os包 [d for d in os.listdir('C://Program Files')] # 里面放入C盘目录 #选取大家C 盘 的文件安装目录 #之前迭代 循环dict 里面的key value 也可以用列表表达式完成 d = {'x': 'A', 'y': 'B', 'z': 'C' } [k + ':' + v for k, v in d.items()] #['x:A', 'y:B', 'z:C'] #把一个list中所有的字符串变成小写 L = ['Hello', 'World', 'IBM', 'Apple'] [x.lower() for x in L] #['hello', 'world', 'ibm', 'apple'] ''' 练习 如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错: >>> L = ['Hello', 'World', 18, 'Apple', None] >>> [s.lower() for s in L] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <listcomp> AttributeError: 'int' object has no attribute 'lower' 使用内建的isinstance函数可以判断一个变量是不是字符串: >>> x = 'abc' >>> y = 123 >>> isinstance(x, str) True >>> isinstance(y, str) 111/531 False 请修改列表生成式,通过添加if语句保证列表生成式能正确地执行: # -*- coding: utf-8 -*- L1 = ['Hello', 'World', 18, 'Apple', None] ---- L2 = ??? ---- # 期待输出: ['hello', 'world', 'apple'] print(L2) ''' L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [s.lower() for s in L1 if isinstance(s, str)] print (L2)