Materials
Materials

Reputation: 149

How can I find the indices of the sublists in my list with the same elements?

I have a list of different sublists:

lst = [
    ['Alex', 'Peeters', 22],
    ['Jim', 'West', 22],
    ['Alex', 'Wesley', 25],
    ['Jim', 'West', 24]
]

How can I find the indices of the sublists in my list with the same first name and surname so I can delete the one with the highest age?

So in this case lst[1][0] == lst[3][0] and lst[1][1] == lst[3][1] because lst[1][2] < lst[3][2] lst.remove[3]

I've got already this, but then I get an IndexError because my len(lst) changes wile removing.

for i in range (len(lst)):
  for j in range (len(lst)):
    if lst[i][0] == lst [j][0] and lst[i][1] == lst [j][1] and i != j:
      if lst[i][2] < lst[j][2]:
           lst.remove(lst[j])
      else:
            lst.remove(lst[i])

Upvotes: 2

Views: 66

Answers (4)

adch99
adch99

Reputation: 340

You could store the sublists to remove in another list and remove them after finding all to be removed.

to_remove = []
for i in range (len(lst)):
  for j in range (len(lst)):
    if lst[i][0] == lst [j][0] and lst[i][1] == lst [j][1] and i != j:
      if lst[i][2] < lst[j][2]:
           to_remove.append(j)
      else:
            to_remove.append(i)
for sublist in to_remove:
    lst.pop(sublist)

This makes it a bit lengthy but easier to understand and debug.

Upvotes: 2

Tanveer Alam
Tanveer Alam

Reputation: 5275

This could be one way to achieve this:

lst = [['Alex', 'Peeters', 22], ['Jim', 'West', 22],['Alex', 'Wesley', 25],['Jim', 'West', 24]]

result = []

for each in set(map(lambda x: tuple(x[:2]), lst)):
    _min_lst = []
    for i in range(len(lst)):
        if each[0] in lst[i] and each[1] in lst[i]:
            _min_lst.append(lst[i][2])
    result.append(list(each)+[min(_min_lst)])

print result

Yields:

[['Alex', 'Peeters', 22], ['Jim', 'West', 22], ['Alex', 'Wesley', 25]]

Upvotes: 1

Bhargav Rao
Bhargav Rao

Reputation: 52151

You can use itertools.groupby within a list comprehension if the order of the elements is not of importance

>>> [min(y) for x,y in itertools.groupby(sorted(lst), key = lambda x:x[:2])]
[['Alex', 'Peeters', 22], ['Alex', 'Wesley', 25], ['Jim', 'West', 22]]

Upvotes: 3

Jo&#227;o Paulo
Jo&#227;o Paulo

Reputation: 6690

another solution...

items_to_remove = []
i, j = 0, 0
for x in lst:
    j = 0
    for y in lst:
        if x[0] == y[0] and x[1] == y[1] and i != j and x[2] >= y[2]:
            items_to_remove.append(x)
        j += 1
    i += 1


for item in items_to_remove:
    lst.remove(item)

Upvotes: 0

Related Questions