3

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.

11
  • By difference, do you consider position also? Commented Jun 29, 2020 at 6:45
  • Lewis Hepburn, Position shouldn't we consider only value of elements Commented Jun 29, 2020 at 6:48
  • So is ['1', '2'] the same as ['2', '1']? Commented Jun 29, 2020 at 6:49
  • Ok, Please see answer. Thanks. Commented Jun 29, 2020 at 6:50
  • Lewis Hepburn, actually in my case I am looking for Cartesian kind of comparison by this method it will be multiple line of code right? Commented Jun 29, 2020 at 6:52

4 Answers 4

2

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']
Sign up to request clarification or add additional context in comments.

Comments

0
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']]

Comments

0

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.