How can I compare two ordered lists in python? - python

If I have one long list: myList = [0,2,1,0,2,1] that I split into two lists:
a = [0,2,1]
b = [0,2,1]
how can I compare these two lists to see if they are both equal/identical, with the constraint that they have to be in the same order?
I have seen questions asking to compare two lists by sorting them, but in my specific case, I am not checking for a sorted comparison, but identical list comparison.

Just use the classic == operator:
>>> [0,1,2] == [0,1,2]
True
>>> [0,1,2] == [0,2,1]
False
>>> [0,1] == [0,1,2]
False
Lists are equal if elements at the same index are equal. Ordering is taken into account then.

If you want to just check if they are identical or not, a == b should give you true / false with ordering taken into account.
In case you want to compare elements, you can use numpy for comparison
c = (numpy.array(a) == numpy.array(b))
Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.

The expression a == b should do the job.

Related

Why does "==" comparison return False even though tuple and list contain same values?

I tried following code:
T = ('a','b','c')
L = list(T)
print(T == L) #Output: False
I ran PythonTutor for visualization and got:
Now it is clear to me why T is L returns False. But since T,L contain the exact same values for each element, I am confused why the == comparison returns False.
('a','b','c') == ['a','b','c'] returns False because a comparison between a list and a tuple always returns False, regardless of their contents. This is documented at https://docs.python.org/3/reference/expressions.html#value-comparisons:
Sequences (instances of tuple, list, or range) can be compared only within each of their types, with the restriction that ranges do not support order comparison. Equality comparison across these types results in inequality, and ordering comparison across these types raises TypeError.

Exact string matching in python - Comparison of two list elements

I'm trying to compare two list-elements in python. If the two elements match exactly, true should be returned, otherwise false.
The elements look like this:
list1_element_1: ['GigabitEthernet0/6/4/1']
list2_element_1: ['GigabitEthernet0/6/4/1.100']
I tried multiple ways of comparing these two elements, including regex.
The following is the function I use to compare the elements:
def find_word(text,search):
result = re.findall('\\b'+search+'\\b', text)
if len(result)>0:
return True
else:
return False
Expected results:
find_word('GigabitEthernet0/6/4/1.100','GigabitEthernet0/6/4/1') FALSE
Actual results:
find_word('GigabitEthernet0/6/4/1.100','GigabitEthernet0/6/4/1') TRUE, because 'GigabitEthernet0/6/4/1' is existing in element 'GigabitEthernet0/6/4/1.100', I guess?
True should only be returned if both list elements are exactly the same!
Thanks!
I hate to tell you this, but you're overthinking it - you can just use the regular == operator for this:
list1_element_1: ['GigabitEthernet0/6/4/1']
list2_element_1: ['GigabitEthernet0/6/4/1.100']
list3_element_1: ['GigabitEthernet0/6/4/1']
print(list1_element_1 == list2_element_1) # False
print(list1_element_1 == list3_element_1) # True
For strings, the == operator returns True if they match exactly. For lists, it returns True if the lengths are the same and corresponding elements match exactly (the .__eq__() method is used for this comparison, if you're trying to compare custom classes - all built-in classes have their notions of equality implemented). So if you have a list of strings, you can test whether or not it's equal to another list of strings:
print(['str1', 'str2', 'str3'] == ['str1', 'str2', 'str3']) # True
print(['str1', 'str2', 'str3'] == ['str1', 'str3', 'str2']) # False
Just use:
def find_word(text, search):
return text == search

Checking if two lists share at least one element [duplicate]

This question already has answers here:
Test if lists share any items in python
(9 answers)
Closed 4 years ago.
I have two lists, for example:
a = ["mail1", "mail2", "mail3", "mail4"]
b = ["mail2", "mail5"]
and I want to check if any of the elements in list b also appears in list a.
I wanted to know if there is a way (and what is it) to do this without a for loop.
Also I wanted to know how can I create a list of boolean values, where each value will be the result of the comparison of values a[i] and b[i], something like:
[z for i, j in zip(a, b) z = i == j] # (just with the right syntax)
z will be 1 if in some place i == j, so I can check the array for any 'True' values.
You can use any:
any(x in a for x in b)
The nice thing about this generator expression is that any will return True as soon as the generator yields a True, i.e. there won't be redundant x in a lookups.
Edit:
You can improve the time complexity by making a set from a.
a_set = set(a)
any(x in a_set for x in b)
Regarding your new question:
[x == y for x,y in zip(a,b)]
Elegant way is to use sets:
a = ["mail1", "mail2", "mail3", "mail4"]
b = ["mail2", "mail5"]
anb = set(a) & set(b)
print anb
if anb:
print True
>>> set(['mail2'])
>>> True
The any function takes in an iterable (See documentation here), so the answer should be any([x in a for x in b])

Check if two variables have values from two different sets, the DRY way

I have a range of values (L,R,U,D) and two variables, d and newd, containing one of them. I need to check if d and newd are in the same subset (L,R or U,D) or not.
I know I can do this:
d in {'L','R'} and newd in {'U','D'} or d in {'U','D'} and newd in {'L','R'}
this indeed returns False if they both have values in L,R or U,D, and True otherwise. Still, I find it much reduntant. Some suggestions about a more DRY approach?
If you know that there are only two sets and that your values must be in one or the other, then you can simplify it to this:
(d in set1) == (newd in set2)
Explanation:
If d is in set 1 and newd is in set 2, both sides of the == are True, so the expression returns True.
If d is in set 2 and newd is in set 1, both sides of the == are False, so the expression returns True.
If they are in the same set, one side of the == will return False and the other True so the result of the expression will be False.
How about:
In [8]: dmap = {'L':0, 'R':0, 'U':1, 'D':1}
In [9]: dmap[d] != dmap[newd]
Out[9]: False

How can I test if a list contains another list with particular items in Python?

I have a list of lists and want to check if it already contains a list with particular items.
Everything should be clear from this example:
list = [[1,2],[3,4],[4,5],[6,7]]
for test in [[1,1],[1,2],[2,1]]:
if test in list:
print True
else:
print False
#Expected:
# False
# True
# True
#Reality:
# False
# True
# False
Is there a function that compares the items of the list regardless how they are sorted?
What you want to use is a set:
set([1,2]) == set([2,1])
returns True.
So
list = [set([1,2]),set([3,4]),set([4,5]),set([6,7])]
set([2,1]) in list
also returns True.
If they're really sets, use the set type
# This returns True
set([2,1]) <= set([1,2,3])
<= means 'is a subset of' when dealing with sets. For more see the operations on set types.
if you want to get [1,2] = [2,1] you should not use list. Set is the correct type. In list, the order of the components matter, in set they don't. That's why you don't get 'False True True'.

Categories

Resources