Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements when satisfying certain condition

I have a large list:

a=[[4,34,1], [5,87,2], [2,76,9],...]

I want to compare all pairs of sub-lists, such that if

a[i][0]>a[j][0] and a[i][1]>a[j][1]

then the sub-list a[i] should be removed. How could I achieve this goal in Python 2.7?

like image 624
user3034556 Avatar asked Dec 14 '25 02:12

user3034556


1 Answers

Here's a slightly more idiomatic way of implementing @MisterMiyagi approach:

drop = set()
for i, j in itertools.combinations(range(len(a)), 2):
    # I would've used ``enumerate`` here as well, but it is
    # easier to see the filtering criteria with explicit 
    # indexing.
    if a[i][0] > a[j][0] and a[i][1] > a[j][1]:
        drop.add(i)

a = [value for idx, value in enumerate(a) if idx not in drop]
print(a)

How is it more idiomatic?

  • Combinatorial iterator from itertools instead of a double forloop.
  • No extra 0: in slices.
  • enumerate instead of explicit indexing to build the answer.

P.S. This is a O(N^2) solution so it might take a while for large inputs.

like image 63
Sergei Lebedev Avatar answered Dec 15 '25 17:12

Sergei Lebedev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!