列表推导式简单明了,但要注意if条件的位置。
#if写在前面
c = [i if i%2==0 else 1 for i in a] //遍历a的每个元素,如果i为偶数直接返回,否则直接返回1。此处if写在for前面要求必须有else项
>>> a = [1,2,3]
>>> c = [i if i%2==0 else 1 for i in a]
>>> c
[1, 2, 1]
#if语句写在末尾
>>> a = [1,2,3]
>>> c = [i for i in a if i%2==0]#if条件在末尾,只筛选出符合条件的数字
>>> c
[2]
#结合lambda
data['sub_orders'] = data['sub_orders'].map(lambda x: [item['item_name'] for item in x] if len(x)>0 else x)