三元表达式与列表解析
三元表达式
三元表达式语法模式:
条件成立的结果 + 条件判断 + 条件不成立的结果
示例:
>>> x = 5
>>> y = 3
>>> res = 'aaa' if x > y else 'bbb'
>>> res
'aaa'
>>> x=3
>>> y=6
>>> res = 'aaa' if x > y else 'bbb'
>>> res
'bbb'
>>>
def max2(x,y):
return x if x > y else y
print(max(3,5))
列表解析
列表解析就是高效的生成列表的方式。
示例:
#生成一个1..10内奇数列表
普通方法:
l = []
for i in range(1,11):
if i % 2 == 1:
l.append(i)
print(l)
#执行结果:
[1, 3, 5, 7, 9]
#列表解析方法:
>>> [i for i in range(1,11) if i % 2 == 1]
[1, 3, 5, 7, 9]
>>>
其它列表解析:
>> x = [[1,2,3],[4,5,6],[7,8,9]]
>>> [i[0]for i in x]
[1, 4, 7]
>>> [(i[0],i[1]) for i in x]
[(1, 2), (4, 5), (7, 8)]
>>> dict([(i[0],i[1]) for i in x])
{1: 2, 4: 5, 7: 8}
>>> [{'name':i[0],'age':i[1],'sex':i[2]} for i in x]
[{'name': 1, 'age': 2, 'sex': 3}, {'name': 4, 'age': 5, 'sex': 6}, {'name': 7, 'age': 8, 'sex': 9}]
>>>
>>> x = ['name','age','sex']
>>> y = [{'name':'tom','age':20,'sex':'male'},{'name':'kom','age':50,'sex':'male'},{'name':'lucy','age':18,'sex':'female'}]
>>> [{j:i[j]} for i in y for j in x]
[{'name': 'tom'}, {'age': 20}, {'sex': 'male'}, {'name': 'kom'}, {'age': 50}, {'sex': 'male'}, {'name': 'lucy'}, {'age': 18}, {'sex': 'female'}]
>>>