I have one list with boolean values like
lyst = [True,True,False,True,False]
and two different lists for example like:
car = ['BMW','VW','Volvo']
a = ['b','c']
I just want to replace True with the values from car
and False with the values from a
.
or make a new list with the sequence from lyst
and values from car
and a
.
The result should be
[BMW,VW,b,Volvo,c].
my code so far:
for elem1,elem2,elem3 in zip(lyst,car,a):
subelem2=elem2
subelem3=elem3
if elem1 != True:
result_list.append(subelem2)
else:
result_list.append(subelem3)
but this creates a list match longer than 5.
How can i do this?
car = iter(car)
a = iter(a)
[next(car) if item else next(a) for item in lyst]
Ok, I couldn't help myself:
car = iter(car)
a = iter(a)
[(flag and next(car)) or next(a) for flag in lyst]
This makes use of some boolean expression features:
and
expression will NOT evaluate the second operand if the first operand is Falseand
expression will return the second operand (the actual object) if both operands evaluate to Trueor
expression will return the first object that evaluates to TrueA potential problem would be if any items in car
or a
evaluate to False. Also this isn't as readable as the ternary in the first solution.
But it was fun.
I guess I'll add that after looking at this again, I probably shouldn't have reassigned the original list names - I should have chosen something different for the iterator names. Once exhausted, the iterators cannot be reset and since the list names were reassigned, the original list information is lost.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With