简体   繁体   中英

python check two lists are equal using a not equal

I am new to the python. I have two lists:

l1 = [1,1,1]
l2 = [1,1,1]

Now, I have to check whether these two are equal or not. I have a solution which I am currently using:

def comp(l1,l2):
    #condition we are checking [1,1,1] and  [1,1,1]
    try:
        a= set(l1)  #converting a list into set , as set will return the length on basis of unique elements.
        b= set(l2)
        return ((a == b) and (len(a) == 1) and (len(b) == 1))
    except TypeError:
        return False

Now, with this I am able to solve the task. But I am trying to do it elementwise.

l1 = [1,1,12]
l2 = [1,1,1]

Then I can treat the 12 as a 1 so I need to know which number is not matching. Can any one help me with this?

Assuming they have the same length, you could do:

{i: (v, l2[i]) for i, v in enumerate(l1) if v != l2[i]}

which returns

{2: (12, 1)}

for you example above. The keys are the indices, the values are tuples of the respective values in the lists.

If you need to know if the two list are exactly the same you can do l1 == l2 directly.

If you need to compare the lists element-wise (assuming they have the same length) and you only play with list of numbers, you can use numpy arrays:

import numpy as np

l1 = np.array([1,1,12])
l2 = np.array([1,1,1])

l1 == l2 # array([ True, True, False])

Assuming the lists are always the same length, You can do:

is_all_equel = True
for i in range(len(l1)):
    if l1[i] != l2[i]:
        print("index " + str(i) + " is " + str(l1[i]) + " in list 1, and " + str(l2[i]) + " in list 2")
        is_all_equel = False

In is_all_equel will be the answer if all the elements in the lists are equel

something like:

l1 = [1,1,12]
l2 = [1,1,1]
for elem in l1:
    if not elem in l2:
        print(elem)
        print(l1.index(elem))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM