Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - replace the boolean value of a list with the values from two different lists [duplicate]

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?

like image 286
Yuli Avatar asked Feb 03 '17 16:02

Yuli


1 Answers

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:

  • a boolean and expression will NOT evaluate the second operand if the first operand is False
  • a boolean and expression will return the second operand (the actual object) if both operands evaluate to True
  • a boolean or expression will return the first object that evaluates to True

A 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.

like image 123
wwii Avatar answered Oct 13 '22 04:10

wwii