标签:对象 class 写法 条件 一个 int exp col and
列表解析式因编译器进行优化,提高了效率,减少出错,增加可读性
示例1:
生成一个列表,元素0-9,对每一个元素自增1后求平方返回新列表
#通常写法为: new = [] for i in range(10): new.append((i+1)**2) print(new) #使用列表解析式方法: new = [(i+1)**2 for i in range(10)] print(new)
输出结果相同:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
示例2:
获取10以内的偶数
list = [i for i in range(10) if i % 2 == 0]
输出结果为:
[0, 2, 4, 6, 8]
示例3:
20以内,即能被2整除又能被3整除的数
#以下两种方法都可以
list1 = [i for i in range(20) if i % 2 == 0 if i % 3 == 0] #方法一 list2 = [i for i in range(20) if i % 2 == 0 and i % 3 == 0] #方法二
list = []
for i in iterableA:
for j in iterableB:
list.append(expr)
示例1:
list1 = [(x,y) for x in "abc" for y in range(3)] list2 = [[x,y] for x in "abc" for y in range(3)] list3 = [{x:y} for x in "abc" for y in range(3)] print(list1) print(list2) print(list3)
输出为:
[(‘a‘, 0), (‘a‘, 1), (‘a‘, 2), (‘b‘, 0), (‘b‘, 1), (‘b‘, 2), (‘c‘, 0), (‘c‘, 1), (‘c‘, 2)] [[‘a‘, 0], [‘a‘, 1], [‘a‘, 2], [‘b‘, 0], [‘b‘, 1], [‘b‘, 2], [‘c‘, 0], [‘c‘, 1], [‘c‘, 2]] [{‘a‘: 0}, {‘a‘: 1}, {‘a‘: 2}, {‘b‘: 0}, {‘b‘: 1}, {‘b‘: 2}, {‘c‘: 0}, {‘c‘: 1}, {‘c‘: 2}]
示例2:
#以下三种输出一样,但推荐使用第一种方法,效率更高 list1 = [(i,j) for i in range(7) if i>4 for j in range(20,25) if j >23] list2 = [(i,j) for i in range(7) for j in range(20,25) if i>4 if j >23] list3 = [(i,j) for i in range(7) for j in range(20,25) if i>4 and j >23] print(list1) print(list2) print(list3)
输出结果为:
[(5, 24), (6, 24)] [(5, 24), (6, 24)] [(5, 24), (6, 24)]
返回1-10的平方列表
l1 = [ i**2 for i in range(1,11)]
有一个列表list = [1,4,9,16,2,5,10,15],生成一个新列表。要去新列表元素是lst相邻2项的和
lst = [1,4,9,16,2,5,10,15] l2 = [lst[i]+lst[i+1] for i in range(len(lst)-1)]
用列表解析式方法打印九九乘法表:
[print(‘{}*{}={:<3}‘.format(j,i,j*i),end=‘\n‘ if i == j else ‘‘) for i in range(1,10) for j in range(1,i+1)]
标签:对象 class 写法 条件 一个 int exp col and
原文地址:https://www.cnblogs.com/rivendare/p/9493698.html