AEinstein
AEinstein

Reputation: 143

Elements corresponding to conditions in a sublist in Python

I have lists J and cond1. I want to print the values in J corresponding to False in each sublist of cond1. I present the current and expected outputs.

J=[[1, 2, 4, 6, 7], [1, 4]]
cond1=[[[False, True, False, True, False]], [[False, True]]]

result = [value for value, condition in zip(J, cond1) if not condition]
print(result)

The current output is

[]

The expected output is

[[1,4, 7],[1]]

Upvotes: 2

Views: 65

Answers (3)

According your question, the expected output should to be [[1,4,7],[1]]

This match your requirement:

J=[[1, 2, 4, 6, 7], [1, 4]]
cond1=[[[False, True, False, True, False]], [[False, True]]]

values = [[x for x, y in zip(j, c[0]) if not y] for j, c in zip(J, cond1)]
print(values)

Upvotes: 0

Tomer Ariel
Tomer Ariel

Reputation: 1537

The problem is that the lists in cond1 are nested inside another list, whereas in J they are at the top level. This is what's causing the confusion. If you were to fix the nesting everything works, as seen here:

J=[[1, 2, 4, 6, 7], [1, 4]]
cond1=[[False, True, False, True, False], [False, True]]
# note that J and cond1 have the same nesting level here

def retain_false(numbers, booleans):
    return [num for num, boolean in zip(numbers, booleans) if not boolean]

for numbers, booleans in zip(J, cond1):
    print(retain_false(numbers, booleans))

## output
[1, 4, 7]
[1]

If, for some reason, you don't want to handle the nesting issue, then just access the first index of booleans:

for numbers, booleans in zip(J, cond1):
    print(retain_false(numbers, booleans[0]))

Upvotes: 4

Lorenzo Bassetti
Lorenzo Bassetti

Reputation: 945

try a old but gold for loop. there might be more elegant solutions, but if the two lists are small, it can be totally fine ..

J = [[1, 2, 4, 6, 7], [1, 4]]
cond1 = [[[False, True, False, True, False]], [[False, True]]]

for j, c in zip(J, cond1):
    values = [x for x, y in zip(j, c[0]) if not y]
    print(values)

this returns

[1, 4, 7]
[1]

The expected result from the user cannot be correct, element '7' is False as well. Am I missing something ?

Upvotes: 2

Related Questions