概述
--coding:utf-8--
Author : 妙玄
File :Generative_formula.py
在这里插入代码片
1. 列表生成式
lis = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
new_lis = [element.upper().replace(‘_’, ‘’) for element in lis if element in lis]
print(new_lis)
2. 字典生成式
keys = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
dic = {key: None for key in keys if key in keys}
print(dic)
items = [(‘name’, ‘egon’), (‘age’, 19), (‘gender’, ‘male’)]
new_dic = {k:v for k,v in items if k != ‘gender’}
print(new_dic)
3. 集合生成式
keys = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
set_ = {key for key in keys if key in keys}
print(set_)
4. 生成器生成式
g = (i for i in range(10) if i > 3) # 此刻在g的内部一个值也没有
print(g)
print(next(g))
5. 案例 统计文件中的字符数
with open(r’D:Generative_formula.md’, mode=‘rt’,encoding=‘utf-8’) as f:
# 方案一:
# count = 0
# for line in f:
# # print(len(line))
# count += len(line)
# print(count)
# 方案二:效率最高
res = sum(len(line) for line in f)
print(res)
最后
以上就是光亮苗条为你收集整理的python列表生成式--coding:utf-8--Author : 妙玄File :Generative_formula.py在这里插入代码片1. 列表生成式2. 字典生成式3. 集合生成式4. 生成器生成式5. 案例 统计文件中的字符数的全部内容,希望文章能够帮你解决python列表生成式--coding:utf-8--Author : 妙玄File :Generative_formula.py在这里插入代码片1. 列表生成式2. 字典生成式3. 集合生成式4. 生成器生成式5. 案例 统计文件中的字符数所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复