1

I have this situation:

main_list = [12, 10, 30, 10, 11,10, 31]
get_indices = [1, 0, 1, 1, 0, 0, 0]

What I want to do is, extract elements from main_list according to the boolean value in get_indices. I tried the following but it is not working :

result = main_list[bool(get_indices)]
print result
10

It should be 12, 30, 10

2 Answers 2

3

I just came across compress() which is best suited for this task. compress() generates an iterator for efficient looping.

from itertools import compress

main_list = [12, 10, 30, 10, 11,10, 31]
get_indices = [1, 0, 1, 1, 0, 0, 0]

print list(compress(main_list, get_indices))
[12, 30, 10]
Sign up to request clarification or add additional context in comments.

Comments

2

You can use list comprehension -

result = [x for i, x in enumerate(main_list) if get_indices[i]]

You do not need to use bool() , 0 is considered False-like in boolean context, and anything non-zero is True-like.

Example/Demo -

>>> main_list = [12, 10, 30, 10, 11,10, 31]
>>> get_indices = [1, 0, 1, 1, 0, 0, 0]
>>> result = [x for i, x in enumerate(main_list) if get_indices[i]]
>>> result
[12, 30, 10]

Or if you really want something similar to your method, since you say -

But if I was able to get my method working, I could also do for example : result = main_list[~bool(get_indices)] to get : [10, 11, 10, 31]

You can use numpy , convert the lists to numpy arrays. Example -

In [30]: import numpy as np

In [31]: main_list = [12, 10, 30, 10, 11,10, 31]

In [32]: get_indices = [1, 0, 1, 1, 0, 0, 0]

In [33]: main_array = np.array(main_list)

In [34]: get_ind_array = np.array(get_indices).astype(bool)

In [35]: main_array[get_ind_array]
Out[35]: array([12, 30, 10])

In [36]: main_array[~get_ind_array]
Out[36]: array([10, 11, 10, 31])

3 Comments

hint: if you're having difficulties reading this, imagine () around (x for i,x in enumerate(main_list)); then it's clear what's the thing that get's first generated before getting checked with if ... Just imagine that, though; won't work as real code.
Correct. But if I was able to get my method working, I could also do for example : result = main_list[~bool(get_indices)] to get : [10, 11, 10, 31]
@DarshanChaudhary For that you can use numpy . Updated answer with example for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.