Reputation: 501
I want to join a list with a conditional statement such as:
str = "\n".join["a" if some_var is True, "b", "c", "d" if other_var==1, "e"]
Each element has a different conditional clause (if at all) so a normal list comprehension is not suitable in this case.
The solution I thought of is:
lst = ["a" if some_var is True else None, "b", "c", "d" if other_var==1 else None, "e"]
str = "\n".join[item for item in lst if item is not None]
If there a more elegant pythonic solution?
Thanks,
Meir
More explanation: In the above example, if some_var equals to True and other_var equals to 1 I would like to get the following string:
a
b
c
d
e
If some_var is False and other_var equals to 1 I would like to get the following string:
b
c
d
e
If some_var is True and other_var is not equals to 1 I would like to get the following string:
a
b
c
e
Upvotes: 0
Views: 2025
Reputation: 6878
I think this is what you want:
lst=[]
if some_var == True:
lst.append('a')
lst.append('b')
lst.append('c')
if other_var == 1:
lst.append('d')
lst.append('e')
Upvotes: 0
Reputation: 31567
Will this work for you?
items = ['a', 'b', 'c'] if cond1 else ['b', 'c']
items.extend(['d', 'e'] if cond2 else ['e'])
str = '\n'.join(items)
Upvotes: 0
Reputation: 208
If each element should only be added to a list if a condition is met, state each condition separately and add the element if it's met. A list comprehension is for when you have an existing list and you want to process the elements in it in some way.
lst = []
if some_var is True:
lst.append('a')
lst.extend(['b', 'c'])
if other_var == 1:
lst.append('d')
lst.append('e')
Upvotes: 1