arsenal88
arsenal88

Reputation: 1160

Unique list of lists

I have a nested list as an example:

lst_a = [[1,2,3,5], [1,2,3,7], [1,2,3,9], [1,2,6,8]]

I'm trying to check if the first 3 indices of a nested list element are the same as other.

I.e.

if [1,2,3] exists in other lists, remove all the other nested list elements that contain that. So that the nested list is unique.

I'm not sure the most pythonic way of doing this would be.

for i in range(0, len(lst_a)):
    if lst[i][:3] == lst[i-1][:3]:
         lst[i].pop()

Desired output:

lst_a = [[1,2,3,9], [1,2,6,8]]

Upvotes: 1

Views: 83

Answers (4)

Mykola Zotko
Mykola Zotko

Reputation: 17824

You can use a dictionary to filter a list:

dct = {tuple(i[:3]): i for i in lst}
# {(1, 2, 3): [1, 2, 3, 9], (1, 2, 6): [1, 2, 6, 8]}

list(dct.values())
# [[1, 2, 3, 9], [1, 2, 6, 8]]

Upvotes: 0

tobias_k
tobias_k

Reputation: 82899

If, as you said in comments, sublists that have the same first three elements are always next to each other (but the list is not necessarily sorted) you can use itertools.groupby to group those elements and then get the next from each of the groups.

>>> from itertools import groupby
>>> lst_a = [[1,2,3,5], [1,2,3,7], [1,2,3,9], [1,2,6,8]]
>>> [next(g) for k, g in groupby(lst_a, key=lambda x: x[:3])]
[[1, 2, 3, 5], [1, 2, 6, 8]]

Or use a list comprehension with enumerate and compare the current element with the last one:

>>> [x for i, x in enumerate(lst_a) if i == 0 or lst_a[i-1][:3] != x[:3]]
[[1, 2, 3, 5], [1, 2, 6, 8]]

This does not require any imports, but IMHO when using groupby it is much clearer what the code is supposed to do. Note, however, that unlike your method, both of those will create a new filtered list, instead of updating/deleting from the original list.

Upvotes: 1

Bharat Gera
Bharat Gera

Reputation: 820

Going with your approach, Find the below code:

lst=[lst_a[0]]
for li in lst_a[1:]:
    if li[:3]!=lst[0][:3]:
        lst.append(li)
print(lst)

Hope this helps!

Upvotes: 0

Alex Leymarie
Alex Leymarie

Reputation: 68

I think you are missing a loop For if you want to check all possibilities. I guess it should like :

for i in range(0, len(lst_a)):
   for j in range(i, len(lst_a)):
      if lst[i][:3] == lst[j][:3]:
         lst[i].pop()

Deleting while going throught the list is maybe not the best idea you should delete unwanted elements at the end

Upvotes: 0

Related Questions