user2242044
user2242044

Reputation: 9233

slicing a list for list comprehension but keeping sliced values

I would like to replace items[1], items[2], items[3] with a boolean value based on whether or not the value is None. This works but eliminates items[0], items[4], items[5] from the output. I could insert/append the values back in, but I'm thinking there must be a way to do it in a single line.

my_list = [[10,30,None,20,30,40],[10,20,None,10,30,40]]
booleans = [[1 if item is None else 0 for item in each_list[1:-2]] for each_list in my_list]
print booleans

Expected Output:

[[10, 0, 1, 0, 30, 40], [10, 0, 1, 0, 30, 40]]

Upvotes: 3

Views: 2346

Answers (3)

Ffisegydd
Ffisegydd

Reputation: 53698

You are close, you can use enumerate when iterating over your inner lists and test whether the indices are in a set that should be modified. This allows you to easily modify which indices should be tested by simply modifying the tests set, and doesn't require some form of slicing which is difficult to modify easily.

my_list = [[10,30,None,20,30,40],[10,20,None,10,30,40]]
tests = {1, 2, 3}

new_list = [[v if i not in tests else 1 if v is None else 0 for i, v in enumerate(x)] 
            for x in my_list]

print(new_list)
# [[10, 0, 1, 0, 30, 40], [10, 0, 1, 0, 30, 40]]

Personally though, I wouldn't use a list comprehension in this case as it's ugly. The code below does exactly the same and is much more readable:

my_list = [[10,30,None,20,30,40],[10,20,None,10,30,40]]
tests = {1, 2, 3}

for x in my_list:
    for i, v in enumerate(x):
        if i in tests:
            x[i] = 1 if v is None else 0

print(my_list)
# [[10, 0, 1, 0, 30, 40], [10, 0, 1, 0, 30, 40]]

Upvotes: 5

Kasravnd
Kasravnd

Reputation: 107347

You need to add the rest of list (that you don't want to replace its elements ) to your edited sub_list :

>>> booleans = [each_list[0:1]+[1 if item is None else 0 for item in each_list[1:-2]]+each_list[4:] for each_list in my_list]
>>> print booleans
[[10, 0, 1, 0, 30, 40], [10, 0, 1, 0, 30, 40]]

Upvotes: 1

Aran-Fey
Aran-Fey

Reputation: 43246

using nested list comprehensions:

booleans= [[l[0]]+[1 if i is None else 0 for i in l[1:4]]+l[4:] for l in my_list]

Upvotes: 2

Related Questions