Remove sequential repeats from python list
Question:
I have a list of tuples. First element is index. I need to delete tuples which has subsequent indexes only leaving first tuple from each sequence:
In:
[
[0, 100],
[1, 200],
[5, 600],
[6, 300],
[7, 800],
[9, 300],
[11, 100],
[14, 300],
]
Out:
[
[0, 100],
[5, 600],
[9, 300],
[11, 100],
[14, 300],
]
Answers:
Using a simple loop (and assuming l
the input list):
prev = -float('inf')
out = []
for x in l:
if x[0]>prev+1:
out.append(x)
prev=x[0]
output: [[0, 100], [5, 600], [9, 300], [11, 100], [14, 300]]
well you need to group the data in based on their difference ie it should be 1. and then from that list add first element in final result.
data = [
[0, 100],
[1, 200],
[5, 600],
[6, 300],
[7, 800],
[9, 300],
[11, 100],
[14, 300],
]
result =[]
data2 = sorted(data, key = lambda x:x[0])
tmp = []
for a in data2:
if not tmp:
tmp.append(a)
else:
val = tmp[-1]
if a[0]-val[0] ==1:
tmp.append(a)
else:
result.append(tmp[0] )
tmp =[a]
if tmp:
result.append(tmp[0])
print(result)
output
[[0, 100], [5, 600], [9, 300], [11, 100], [14, 300]]
I have a list of tuples. First element is index. I need to delete tuples which has subsequent indexes only leaving first tuple from each sequence:
In:
[
[0, 100],
[1, 200],
[5, 600],
[6, 300],
[7, 800],
[9, 300],
[11, 100],
[14, 300],
]
Out:
[
[0, 100],
[5, 600],
[9, 300],
[11, 100],
[14, 300],
]
Using a simple loop (and assuming l
the input list):
prev = -float('inf')
out = []
for x in l:
if x[0]>prev+1:
out.append(x)
prev=x[0]
output: [[0, 100], [5, 600], [9, 300], [11, 100], [14, 300]]
well you need to group the data in based on their difference ie it should be 1. and then from that list add first element in final result.
data = [
[0, 100],
[1, 200],
[5, 600],
[6, 300],
[7, 800],
[9, 300],
[11, 100],
[14, 300],
]
result =[]
data2 = sorted(data, key = lambda x:x[0])
tmp = []
for a in data2:
if not tmp:
tmp.append(a)
else:
val = tmp[-1]
if a[0]-val[0] ==1:
tmp.append(a)
else:
result.append(tmp[0] )
tmp =[a]
if tmp:
result.append(tmp[0])
print(result)
output
[[0, 100], [5, 600], [9, 300], [11, 100], [14, 300]]