muammar muammar - 1 month ago 11
Python Question

Comparing and discarding two consecutive elements not complying certain condition in a list using Python

So I have this list in Python that I am showing below, and for the sake of simplicity I'll name it as

p
:

[[11 10]
[12 9]
[13 9]
[13 10]
[14 8]
[14 10]
[15 7]
[15 9]
[16 8]
[17 7]
[18 2]
[18 8]
[19 1]
[19 7]
[20 1]
[20 2]
[21 2]
[21 4]
[22 1]
[22 3]
[23 4]
[24 3]
[25 4]
[25 6]
[26 3]
[26 5]
[27 5]
[27 6]
[28 8]
[28 10]
[29 6]
[30 5]
[31 7]
[31 9]
[32 1]
[32 2]
[33 4]
[33 6]
[34 3]
[34 5]]


What I am trying to do is to compare consecutive pairs and then let only the elements with the same
p[0]
. In this sense, one can note that the pairs with
p[0]= 11,12,16,17,23,24,29,30
will not survive and then
p
will become:

[[13 9]
[13 10]
[14 8]
[14 10]
[15 7]
[15 9]
[18 2]
[18 8]
[19 1]
[19 7]
[20 1]
[20 2]
[21 2]
[21 4]
[22 1]
[22 3]
[25 4]
[25 6]
[26 3]
[26 5]
[27 5]
[27 6]
[28 8]
[28 10]
[31 7]
[31 9]
[32 1]
[32 2]
[33 4]
[33 6]
[34 3]
[34 5]]


What would be a way of doing this in python? I'd be glad if somebody could give me an idea.

Answer

Note that the original question was "compare consecutive pairs and then let only the elements with the same p[0]" which means that one should not sort the original list. If the original list is sorted, then pairs which would otherwise not be "consecutive" will be picked up and kept. While the sample list was sorted, I will not assume that to be the case so that this will also handle a case such as

[[13, 5],
 [13, 2],
 [14, 9],
 [13. 6]]

to generate

[[13, 5],
 [13, 2]]

I will show a simple loop in order to make it easier to understand, but list comprehension can make it shorter. Note that Counter requires python 2.7

prev = None
newp = []
length = len(p) - 1
for i in range(length):
  if p[i][0] == p[i+1][0] or p[i][0] == prev:
    newp.append(p[i])
    prev = p[i][0]

if p[length][0] == p[length-1][0]:
  newp.append(p[length])

This will create the new list as you want