简体   繁体   中英

Python list comprehension with two lists: evaluate lists

I have two lists:

input_list = ['a','b']
existing_list = ['q','w','r']

I want to create a new list that will be equal to input_list if it's not empty else it should be equal to existing_list .

The easiest way to do this is to use the plain if-else :

if input_list:
  list_to_use = input_list
else:
  list_to_use = existing_list

Is it possible to do this in a list comprehension or in any other manner that is more concise?

list_to_use = [x if input_list else y for y in existing_list for x in input_list]

The closest I could get is with this one that produces ['a', 'b', 'a', 'b', 'a', 'b'] , a wrong result.

You don't need a list comprehension. That's exactly what or operation does:

>>> input_list or existing_list 
['a', 'b']
>>> input_list = []
>>> 
>>> input_list or existing_list 
['q', 'w', 'r']

除此之外or ,通过Kasramvd建议(这应该是做到这一点方式),你也可以使用三元运算符

list_to_use = input_list if input_list else existing_list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM