Mike
Mike

Reputation: 2703

Filter list within a list by a string

I have an array of basketball players that has an array for each player containing data like this:

[[893, "Jordan, Michael", 0, "1984", "2002", "michael_jordan"],[674, "Doe, John", 0, "2009", "2014", "doe_john"]]

I would like to filter this array to only show players who have the year "2014" in their array, so I can get a list of all active players.

Here is the code I'm trying now:

players =  [[893, "Jordan, Michael", 0, "1984", "2002", "michael_jordan"],[674, "Doe, John", 0, "2009", "2014", "doe_john"]]
active = set('2014')
for player in players:
     if players & set(active):
          print active

And the error in the console is:

    Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: unsupported operand type(s) for &: 'list' and 'set'

Can anyone help me out with this? I would really appreciate it!

Upvotes: 0

Views: 40

Answers (1)

user2555451
user2555451

Reputation:

active is a set but player is a list. Using & only works with two set objects, not a list and a set.

However, you should not be using sets for this in the first place because you only want to see if a string is inside a list. For that, you should use a simple in membership test :

players =  [[893, "Jordan, Michael", 0, "1984", "2002", "michael_jordan"],[674, "Doe, John", 0, "2009", "2014", "doe_john"]]
active = '2014'
for player in players:
     if active in player:
          print active

active in player will return True if '2014' is in the list player. Below is a demonstration:

>>> active = '2014'
>>> player = [893, "Jordan, Michael", 0, "1984", "2002", "michael_jordan"]
>>> active in player
False
>>> player = [674, "Doe, John", 0, "2009", "2014", "doe_john"]
>>> active in player
True
>>>

Upvotes: 1

Related Questions