Benjamin Hunt
Benjamin Hunt

Reputation: 23

How can I check if an attribute of a class exists in array?

I want to know if it is possible to check if an array of a class has a specific instance of an attribute, and return True if it does. In other words, does an instance of a class attribute exist in an array of that class?

In my example, I have an array of class Team. The class Team has an attribute, name. I want to check if a Team instance with a specific name exists by iterating over an array of Team instances.

Class Team:

class Team:
    def __init__(self):
        self.name = name  # (String)

[Invalid] This is the how I wanted to write the function:

# team_name is a String variable
# teams is an array of the Team class

def team_name_taken(team_name, teams):
    if team_name in teams.name:
        return True
    else:
        return False

I know this doesn't work, but is it possible to iterate over the same attribute within an array in this fashion?

[Valid] Regarding the goal of my code, I have the following code that works properly:

def team_name_taken(team_name, teams):
    for team in teams:
        if team_name == team.name:
            return True
    return False

I know that this works, I was just wondering if there was another way to do it, similar to the invalid way I represented above.

Upvotes: 0

Views: 1645

Answers (2)

jeschwar
jeschwar

Reputation: 1314

The following class definition allows name from the user to be assigned to the Team.name attribute and forces it to be a str object:

class Team(object):
    def __init__(self, name):
        self.name = str(name)

Here is an example list of Team instances:

teams = [Team(x) for x in range(10)]

You can do what I think you want with some one-liners:

Using another list comprehension to find out if any of the names equal '3':

any([team.name == '3' for team in teams])

Or if you really want to use a function you can use the following:

any(map(lambda obj: obj.name == '3', teams))

Upvotes: 0

Tobias
Tobias

Reputation: 947

What you could do is the following:

def team_name_taken(team_name, teams):
    team_names = [team.name for team in teams]
    if team_name in team_names:
        return True
    else:
        return False

This will generate a list with the items of the list being all team names. Once you have done that you can do if team_name in team_names: and get the desired outcome.

If on the other hand you just want to make it a oneliner you could do this:

def team_name_taken(team_name, teams):
    return len([ team for team in teams if team.name == team_name ]) >= 1

This will make a list then check if the len() of the list is 1 (or bigger) and if that is the case return True else False.

Upvotes: 1

Related Questions