清单理解中的if / else条件

时间:2018-07-20 19:38:45

标签: python python-3.x

如何在单个列表理解行中同时写短名和长名?

#this is how i tried below code but its not working.
short_names, long_names = [(i,j) for i,j in planet_names if len(i) <= 5  
else len(j) > 5 ]

#working code
planet_names = ["Mercury", "Venus", "Earth", "Mars", "Jupiter","Saturn"]                         
short_names = [i for i in planet_names if len(i) <= 5]
long_names = [i for i in planet_names if len(i) > 5]

1 个答案:

答案 0 :(得分:3)

short_names=[]
long_names=[]
planet_names = ["Mercury", "Venus", "Earth", "Mars", "Jupiter","Saturn"]                         
for i in planet_names :
    if len(i) <= 5:
        short_names.append(i) 
    else:
        long_names.append(i)