三元表达式和列表解析
可以很大程度上减少代码量
x=4
y=3
if x>y:
print(x)
else:
print(y)
print('aaa' if x>y else 'bbb')
def max(x,y):
# if x>y:
# return x
# else:
# return y
return x if x>y else y
print(max(5,6))
s='hello'
l=[]
for i in s:
res=i.upper()
l.append(res)
print(l)
a='hello'
res=[i.upper() for i in a]
print(res)
>>>
['H', 'E', 'L', 'L', 'O']
['H', 'E', 'L', 'L', 'O']
l=[1,31,73,84,57,22]
l_new=[]
for i in l:
if i >50:
l_new.append(i)
print(l_new)
res=[i for i in l if i > 50]
print(res)
>>>
[73, 84, 57]
[73, 84, 57]
l=[1,2,3,4,5,10]
print([i for i in l if i > 4 and i < 10])
>>>
[5]