python 容器生成式

列表生成式

l = ['alex_dsb', 'lxx_dsb', 'wxx_dsb', 'xxq', 'egon_dsb']
new_l = []
#  最原始的列表生成式方法
for i in l:
    if i.endswith('_dsb'):
        new_l.append(i)

#  改进后的列表生成式方法
now_l = [name for name in l if name.endswith('sb')]

#  去掉sb 的列表生成式
new_l = [name.replace('sb', '') for name in l]

#  把所有的字符串换成大写
new_l = [name.upper() for name in l]


# 字典生成式
d = [1,2,3,4]
new_d = {k: None for k in d}

# 集合生成式
l = ['name', 'alex', 'egon']
new_l = {key for key in l}

# 元组生成式
l = (i for i in range(1, 10))
print(tuple(l))  # (1, 2, 3, 4, 5, 6, 7, 8, 9)
print(type(l))  # <class 'generator'>


#  生成器表达式
#  统计文件的字符数
#  方式一
f = open('a.txt', 'r+t', encoding='utf-8')
res = 0
for i in f:
    res += len(i)

#  方式二

g = (len(line) for line in f)
print(g)
res = sum(g)
print(res)
res = sum((len(line) for line in f))
# 上述可以简写为如下格式
res = sum(len(line) for line in f)
posted @ 2020-03-25 14:16  nick_xm  阅读(206)  评论(0编辑  收藏  举报