Python之解析式与生成器

2019-07-23  本文已影响0人  EchoPython

1.列表解析式

# 将lst1的元素+100,导入到lst2
lst1 = list(range(10))
lst2 = []
for item in lst1:
    lst2.append(item+100)
print(lst2)   #输出:[100, 101, 102, 103, 104, 105, 106, 107, 108, 109]

#使用列表解析式解析上面例子
new_lst1 = [item + 100 for item in lst1]
print(new_lst1 )  #输出:[100, 101, 102, 103, 104, 105, 106, 107, 108, 109]

#判断item满足被2整除,被3整除,list2和list3的写法都是一样的
list1 = list(range(100))
list2 = [item + 100 for item in list1 if item %2 == 0 and item %3 ==0]
print(list2)  #输出:[100, 106, 112, 118, 124, 130, 136, 142, 148, 154, 160, 166, 172, 178, 184, 190, 196]

list3 = [item + 100 for item in list1 if item % 2 == 0 if item % 3 == 0]
print(list3)  #输出:[100, 106, 112, 118, 124, 130, 136, 142, 148, 154, 160, 166, 172, 178, 184, 190, 196]
lst = []
for i in range(2):
    for j in range(2):
        lst.append((i, j))
print(lst)  #输出:[(0, 0), (0, 1), (1, 0), (1, 1)]

#将上述代码解析
lst = [(i, j) for i in range(2) for j in range(2)]
print(lst)  #输出:[(0, 0), (0, 1), (1, 0), (1, 1)]

lst = [(i,j) for i in range(10) if i>2 for j in range(10,15) if j>13]
print(lst)  #输出:[(3, 14), (4, 14), (5, 14), (6, 14), (7, 14), (8, 14), (9, 14)]

2.集合解析式

set1 = {(x,x+1) for x in range(10)}
print(set1)
#输出:{(0, 1), (1, 2), (7, 8), (6, 7), (4, 5), (5, 6), (8, 9), (9, 10), (2, 3), (3, 4)}

3.字典解析式

# 字典解析式
dict1 = {'{}'.format(x):x for x in range(10)}
print(dict1)   #输出:{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

# 输出三个元素,因为会被key会被覆盖
dict2 = {x:y for x in range(3) for y in range(3)}
print(dict2)  #输出:{0: 2, 1: 2, 2: 2}

# 上式等价于
dict3 = {}
for x in range(3):
    for y in range(3):
        dict3[x] = y
print(dict3)   #输出:{0: 2, 1: 2, 2: 2}

4.什么是生成器

g = (item for item in range(10))
print(g)  #输出:<generator object <genexpr> at 0x0095BBF0>

print(next(g))  #输出:0
print(next(g))  #输出:1
....

5.生成器操作

g = (item for item in range(10))
print(g)  #输出:<generator object <genexpr> at 0x0095BBF0>

value1 = next(g)
print(value1)  #输出:0
value2 = next(g)
print(value2)  #输出:1
print('*'*100) 
for item in g:
    print(item)  #输出:2,3,4,5,6,7,8,9

如果你依然在编程的世界里迷茫,
不知道自己的未来规划,
对python感兴趣,
这里推荐一下我的学习交流圈QQ群:895 797 751,
里面都是学习python的,
上一篇下一篇

猜你喜欢

热点阅读