Skip to content
Advertisement

Unique lists within list of lists if those lists have list as one of the elements

If I have:

l = [['98765', ['Einstein, A', 'SFEN'], 'SSW 540', 3], ['98765', ['Einstein, A', 'SFEN'], 'SSW 540', 3],
     ['98764', ['Feynman, R', 'SFEN'], 'SSW 564', 3], ['98764', ['Feynman, R', 'SFEN'], 'SSW 564', 3]]

What would be the best way to get:

k = [['98765', 'Einstein, A', 'SFEN', 'SSW 540', 3], ['98764', 'Feynman, R', 'SFEN', 'SSW 564', 3]]

If I try:

uniqinstruct = set(map(tuple, l))

I get TypeError: unhashable type: 'list'. I don’t want to remove all layers of nesting, because that would just combine everything into one list:

output = []

def reemovNestings(l):
    for i in l:
        if type(i) == list:
            reemovNestings(i)
        else:
            output.append(i)

reemovNestings(l)
print(sorted(set(output), key=output.index))

Output:

['98765', 'Einstein, A', 'SFEN', 'SSW 540', 3, '98764', 'Feynman, R', 'SSW 564']

If two instructors have the same count (i.e. 3 in this case), then only one 3 remains because it’s a set, and I can’t group the elements of the list by every x intervals. What would be a good way to preserve that last value?

Advertisement

Answer

Given that you know which layer you want to unwrap, you could just iterate through that layer. In your particular example, it’s the second layer:

res = []
for inner_list in l:
    inner = []
    for el in inner_list:
        if type(el) == list:
            inner.extend(el)
        else:
            inner.append(el)
    if not (inner in res):
        res.append(inner)

Note that list.extend adds multiple values to the list.

if not (inner in res): res.append(inner) gives you unique items in the top layer. Thanks to @dmitryro for the tip.

Advertisement