Reputation: 2437
The title might seem a little weird, but here is what I need to do in Python:
Suppose I have a list (L) and a Boolean array (A)
L=[1,2,3,4]
A=[True, False, True]
I need to create a list that will have L where A is True and False, where A is false, i.e.
[[1,2,3,4], False, [1,2,3,4]]
I was thinking about doing something like
L and A
but it does not seem to work since L is not a scalar as I want it to be.
Is there any way to define L as a scalar and accomplish it with one-two lines of code?
Thanks.
Upvotes: 2
Views: 1836
Reputation: 2257
By definition, L
and A
are not scalar. You can use a scalar which iterates over A and returns a vector containing L
where the scalar is True
and containing False
where it is False
.
Using list comprehension:
[L if a else False for a in A] # a is the scalar here.
Using map(...)
:
map(lambda a: L if a else False, A)
Using a for
statement:
returnVector = A[:] # returnVector is the intended output vector
for index, a in enumerate(A): if a is True: returnVector[index] = L
Upvotes: 0
Reputation: 6086
You could use list comprehensions:
[L if i else False for i in A ]
Upvotes: 4
Reputation: 3638
here's a pretty straightforward way to do it:
newList = []
for x in A:
if x is True:
newList.append(L)
else:
newList.append(False)
but since you wanted brevity, here's a one-liner:
[L if x else x for x in A]
Upvotes: 2