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
Related
I am new to python
I have a list of flags. and that list has a variable length. I want to check if all the variables in that list are true
I have tried
if (all in flags[x]==True):
finalFlags[x-1]=True
But that turned the final flag true when only one flag is true
finalFlags = False
if all(flags):
finalFlags=True
Edit: Simplified per comment from Chris:
finalFlags = all(flags)
Since you didn't post an example, i can suppose like this:
my_flags = [True, False, True, True, True, False]
valid_flags = 0
for flag in my_flags:
if flag == True:
valid_flags += 1
if len(my_flags) == valid_flags:
print("Total match")
else:
print("Matched ", valid_flags, " out of ", len(my_flags))
all and any functions can be used to check the boolean values inside the list.
test_list = []
all(iterable) returns True if all elements of the iterable are considered as true values (like reduce(operator.and_, iterable)).
any(iterable) returns True if at least one element of the iterable is a true value (again, using functional stuff, reduce(operator.or_, iterable)).
When you need to check all the values are true then you can use all() function as follow
all(test_list) #will return true
Also, you can use any() to check all values that are true but at this time, You need to convert the list elements from true to false and check whether if any true is there we can say there is a false in original list and we need to return false also when any() returns false which means there is no true value so in the original list we don't have true values
not all(not element for element in data)
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.
doing an exercise on CheckIO and I'm wondering as to why this won't work. Given a set of strings, I'm trying to return True if any of the strings are suffixes of any other string in the set. False otherwise. Using itertools I'm generating the necessary permutations in tuples first. Then for each tuple (each i), I wanted to see the hard way if the second tuple was in the end of the first tuple (option1). The otherway was using the .endwith function (option2), but neither will work for me. Why are these two options flawed?
import itertools
def checkio(words_set):
for i in itertools.permutations(words_set, 2):
#option1 ---- if i[1] in i[0][-len(i[1]):]:
#option2 ---- if i[0].endswith(i[1]):
return True
else:
return False
examples:
checkio({"hello", "lo", "he"}) == True
checkio({"hello", "la", "hellow", "cow"}) == False
I know this works as an answer. But just wondering why my original methods wouldn't take.
def checkio(words_set):
for w1 in words_set:
for w2 in words_set:
if w1.endswith(w2) and w1 != w2:
return True
return False
Your return False should be at the end of the for loop, otherwise the function will return True/False at every first comparison and will ignore all subsequent comparisons:
import itertools
def checkio(words_set):
for i in itertools.permutations(words_set, 2):
if i[0].endswith(i[1]):
return True
return False
Since it's an exercise, I won't give you the full answer, but are you sure that you really want to return False in the else clause?
Its because you return False right after the first check. and if it fails it will returns False you need to put it out of your for loop!
But as a more pythonic way you can use combinations and a generator expression within any function :
>>> from itertools import combinations
>>> s={"hello", "lo", "he"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s,2)))
True
>>> s2={"hello", "la", "hellow", "cow"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s2,2)))
False
I was testing a list to see if it's empty or not. Normally I use len(list) == 0 and I vaguely remembered reading a little while ago that the correct way to test if a list is empty was whether it was True or false.
So I tried list is False, and that returned False. Maybe I'm suppose to be using == ?
Nope, that also returned false. list is True, returned false as did list == True.
Now I'm confused so I do a quick google and end up at: Best way to check if a list is empty
The top answer is:
if not a:
print "List is empty"
So I search around some more and end up in the python manual where 4.1 states:
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
any empty sequence, for example, '', (), [].
Now I'm plain confused. If I test a list as if not list, it works fine. But if an empty list is false, then why can't I just do if list is False or if list == False?
Thanks
An empty list is not False, but when you convert it to a boolean, it converts to False. Likewise for dicts, tuples, strings, etc.:
>>> [] == False
False
>>> bool([]) == False
True
>>> {} == False
False
>>> bool({}) == False
True
When you put something in the condition of an if clause, it is its boolean value that is used for testing the if. That's why if someList is the same as if bool(someList). Likewise, not foo does a boolean not, so not [] equals True.
As other have said, in python bool([]) == False. One thing that is frequently exploited by python programmers is that the operators and and or don't (necessarily) return True/False. Consider the following:
3 and 4 #returns 4
0 and 8 #returns 0 -- This is short-circuit evaluation
0 or 8 #returns 8
True or 0 #returns True -- This is short-circuit evaluation
[] or False #returns False
False or [] #returns []
What happens in an if statement is that the condition gets evaluated as above and then python implicitly calls bool on the result -- So you can think of it as:
if condition:
is the same thing as:
if bool(condition):
as far as python is concerned. Similarly for the not operator:
not condition
is the same thing as
not bool(condition)
mylist is False means "is the object named mylist exactly the same object as False?"
mylist == False means "is the object named mylist equal to False?
not mylist means "does the object named mylist behave falsily?
None of these are equivalent: 1 is not 1.0 but 1 == 1.0 and [] != False but not [] is True.
Comparing the list to False, and testing the list's truth or falsehood aren't quite the same thing. An empty list isn't equal to False, but behaves as False in a boolean context.
Here's another way to say it that might help this make sense:
print (bool([]) == False) # will print True
print ([] == False) # will print False
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'.