Home > front end >  How can I get the unique nested lists of a python list?
How can I get the unique nested lists of a python list?

Time:12-14

My question is related to the uniqueness of lists nested in a main list. Specifically, I have the following structure which is a list which includes lists:

lst = [  [
            [14], ['walk'], [69], ['walk'], [7]
         ],
         [
           [14], ['walk'], [69], ['walk'], [7]
          ],
        [
          [30], [948], [75], [947], [10]
        ],
        [
          [14]
        ]
   ]

In order to get the unique elements of the list I tried το implement the following:

unique_data = [list(x) for x in set(tuple(x) for x in lst)] but I am getting the following error:

TypeError: unhashable type: 'list' .

The expected output is the following:

[[[14], ['walk'], [69], ['walk'], [7]],

[[30], [948], [75], [947], [10]],

[[14]]]

Any suggestions?

CodePudding user response:

lst = [  [            [14], ['walk'], [69], ['walk'], [7]
         ],
         [           [14], ['walk'], [69], ['walk'], [7]
          ],
        [          [30], [948], [75], [947], [10]
        ],
        [          [14]
        ]
   ]

unique_data = []

for element in lst:
    if element not in unique_data:
        unique_data.append(element)

print(unique_data)

This should give you the output you are expecting:

[[[14], ['walk'], [69], ['walk'], [7]], [[30], [948], [75], [947], [10]], [[14]]]

CodePudding user response:

if you create a dict, and saving the values as key, so if order matter than you can solve this problem as

lst = [[[14], ['walk'], [69], ['walk'], [7]], [[14], ['walk'], [69], ['walk'], [7]], [[30], [948], [75], [947], [10]], [[14]]]
 
unique = {}
for sublist in lst:
    key = ''
    for sub_sublist in sublist:
            for value in sub_sublist:
                    key  = '_'   str(value)
    unique[key] = sublist
 
print(unique)
# output -> {'_14_walk_69_walk_7': [[14], ['walk'], [69], ['walk'], [7]], '_30_948_75_947_10': [[30], [948], [75], [947], [10]], '_14': [[14]]}

result = list(unique.values())
print(result)
# output. -> [[[14], ['walk'], [69], ['walk'], [7]], [[30], [948], [75], [947], [10]], [[14]]]

CodePudding user response:

In order to use set(), you need to convert all the lists (and sub-lists) to tuples.

Try this code:

unique = tuple([tuple([tuple(x) for x in y]) for y in lst])
unique = set(unique)
  • Related