How to compare each element of multiple lists and return name of lists which are different

Viewed 59

I am having multiple lists and I need to compare each list with one another and return the name of lists which are different. We need to consider value of elements in list irrespective of their position while comparing lists.

For example:-

Lis1=['1','2','3']

Lis2=['1','2']

Lis3=['0','1','3']

Lis4=[]

Lis5=['1','2']

Output:-

['Lis1','Lis2','Lis3','Lis4']

Thanks in advance.

4 Answers

Try this:

input_lists = {"Lis1": ['1', '2', '3'], "Lis2": ['1', '2'],
               "Lis3": ['0', '1', '3'], "Lis4": [], "Lis5": ['1', '2']}

output_lists = {}

for k, v in input_lists.items():
    if sorted(v) not in output_lists.values():
        output_lists[k] = sorted(v)

unique_keys = list(output_lists.keys())
print(unique_keys)  # ['Lis1', 'Lis2', 'Lis3', 'Lis4']
import itertools

Lis1=['1','2','3']

Lis2=['1','2']

Lis3=['0','1','3']

Lis4=[]

Lis5=['1','2']

k=[Lis1,Lis2,Lis3,Lis4,Lis5]

k.sort()
list(k for k,_ in itertools.groupby(k))

output

[[], ['0', '1', '3'], ['1', '2'], ['1', '2', '3']]

a simple way to implement

Lis1=['1','2','3']
Lis2=['1','2']
Lis3=['0','1','3']
Lis4=[]
Lis5=['1','2']

lis=[Lis1,Lis2,Lis3,Lis4,Lis5]
final=[]
for ele in lis:
    if(ele not in final):
        final.append(ele)
print(final)

with your given data you can use:

Lis1=['1','2','3']

Lis2=['1','2']

Lis3=['0','1','3']

Lis4=[]

Lis5=['1','2']


name_lis = {'Lis1': Lis1, 'Lis2': Lis2, 'Lis3': Lis3, 'Lis4': Lis4, 'Lis5': Lis5}
tmp = set()
response = []

for k, v in  name_lis.items():
    s = ''.join(sorted(v))
    if s not in tmp:
        tmp.add(s)
        response.append(k)
        
print(response)

output:

['Lis1', 'Lis2', 'Lis3', 'Lis4']

name_lis dictionary contains the name of your list and the actual list, you are iterating over each list, and for each list, you are sorting the elements and then converting in a string, if the string was encountered before you know that the list is a duplicate if not you are adding the list to the response

Related