标签:int turn mod with open 没有 line encoding 格式 class
def func(x,y):
if x > y:
return x
else:
return y
res=func(1,2)
print(res)
语法格式: 条件成立时要返回的值 if 条件 else 条件不成立时要返回的值
x=1
y=2
# res=x if x > y else
# print(res)
res=111111 if ‘egon‘ == ‘egon‘ else 2222222222
print(res)
# 应用举例
def func():
# if 1 > 3:
# x=1
# else:
# x=3
x = 1 if 1 > 3 else 3
l = [‘alex_dsb‘, ‘lxx_dsb‘, ‘wxx_dsb‘, "xxq_dsb", ‘egon‘]
new_l=[]
for name in l:
if name.endswith(‘dsb‘):
new_l.append(name)
new_l=[name for name in l if name.endswith(‘dsb‘)]
new_l=[name for name in l]
print(new_l)
# 练习
# 把所有小写字母全变成大写
new_l=[name.upper() for name in l]
print(new_l)
# 把所有的名字去掉后缀_dsb
new_l=[name.replace(‘_dsb‘,‘‘) for name in l]
print(new_l)
keys=[‘name‘,‘age‘,‘gender‘]
dic={key:None for key in keys}
print(dic)
items=[(‘name‘,‘egon‘),(‘age‘,18),(‘gender‘,‘male‘)]
res={k:v for k,v in items if k != ‘gender‘}
print(res)
keys=[‘name‘,‘age‘,‘gender‘]
set1={key for key in keys}
print(set1,type(set1))
g=(i for i in range(10) if i > 3)
# 强调:此刻g内部一个值也没有
print(g,type(g))
print(g)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
with open(‘笔记.txt‘, mode=‘rt‘, encoding=‘utf-8‘) as f:
# 方式一:
res=0
for line in f:
res+=len(line)
print(res)
# 方式二:
res=sum([len(line) for line in f])
print(res)
# 方式三 :效率最高
res = sum((len(line) for line in f))
# 上述可以简写为如下形式
res = sum(len(line) for line in f)
print(res)
标签:int turn mod with open 没有 line encoding 格式 class
原文地址:https://www.cnblogs.com/Lance-WJ/p/12567513.html