Sanjay Sharma
Sanjay Sharma

Reputation: 21

changing a nested list with a condition

alpha = [[[1, True], [2, False], [3, True]], [[4, False], [5, True], [6,False]]]

I want to create another nested list (beta) but only with the first elements of each list, i.e: the integers.

The condition is: I want beta to contain elements from alpha only if it's adjacent boolean element is True. If it is false I want to store "o" in its corresponding position.

What I'm looking for:

beta = [[[1, "o", 3], [["o", 5 "o"]]

Upvotes: 2

Views: 292

Answers (2)

schwartz721
schwartz721

Reputation: 1027

List comprehensions will work well here.

beta = [[integer if boolean else 'o' for integer, boolean in item] for item in alpha])

This is a complex line of code, so we can break it down. The inner list comprehension is [integer if boolean else 'o' for integer, boolean in item]. The second part of the comprehension for integer, boolean in item is used to unpack the the list. It takes item, which you'll see in a moment is what we are calling the nested lists, and unpacks the integer into a variable integer, and the boolean value into a variable boolean. It then uses a conditional statement integer if boolean else 'o'. Expanded, that statement is:

if boolean:
    return integer
else:
    return 'o'

The outer list comprehension is simply [<inner comprehension> for item in alpha]. This goes through alpha and passes what it finds to the inner comprehension as a variable called item.

Upvotes: 2

Oli
Oli

Reputation: 2602

This can be acheived using list comprehension and if expressions:

beta = [[(i if condition else 'o') for i, condition in a_elem] for a_elem in alpha]

The i, condition part is list unpacking, similar to here

Upvotes: 4

Related Questions