'Compare a string variable with a string attribute of an object
I have a list of objects that contain information of a user such as their username, userID and other attributes. I have another list that contains strings of usernames. Usernames are unique and will not be identical to another user's.
From these two lists, I would like to find which users are in both lists based on their username.
When comparing the list of strings to the Name attribute of a user object, if two usernames that appear identical are found, the equality check returns false.
For example, if one of the user objects has a Username attribute of "Gerald" and in my list of usernames "Gerald" is an item in that list, when comparing the two it always returns false.
# users is a list of user objects. A user object has a Username attribute that stores a string.
# names is a list of strings of usernames.
for user in users:
for name in names:
# The if statement below always returns false.
if name == user.Name:
# perform desired operations when a match is found here...
break
I do not understand why two strings in this scenario cannot be compared.
Can attributes of an object not be compared to a variable of the same data type?
Solution 1:[1]
You can convert both to sets of strings, and then use & to take the intersection of them. Elements appearing in the intersection are the ones that would be duplicates.
This approach is reasonably fast and should be O(N) on average.
user_names = {u.Name for u in users} # set of strings consisting the names
other_names = set(names) # convert list to set
duplicates = user_names & other_names
for matched_string in duplicates:
this_is_a_match_so_do_things()
Solution 2:[2]
I found a solution that works:
for user in users:
for name in names:
if name.find(user.Name) == 0:
# perform desired operations when a match is found here...
break
Using the str.find() function works but only when it is used on a name in the list of strings, not list of objects.
Doing it the following way always returned false:
for user in users:
for name in names:
if user.Name.find(name) == 0:
# perform desired operations when a match is found here...
break
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eric Jin |
| Solution 2 | Mr Kaos |
