我有一系列篮球运动员,每个球员都有一个数组,其中包含以下数据:
[[893, "Jordan, Michael", 0, "1984", "2002", "michael_jordan"],[674, "Doe, John", 0, "2009", "2014", "doe_john"]]
我想过滤这个数组,只显示数组中有"2014"
年的玩家,这样我就可以获得所有活跃玩家的列表。
以下是我现在尝试的代码:
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
控制台中的错误是:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: unsupported operand type(s) for &: 'list' and 'set'
任何人都可以帮我解决这个问题吗?我真的很感激!
答案 0 :(得分:1)
active
是一个集合,但player
是一个列表。使用&
仅适用于两个设置对象,而不是列表和集合。
但是,您首先不应该使用集合,因为您只想查看字符串是否在列表中。为此,您应该使用简单的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
位于列表True
中, '2014'
将返回player
。以下是演示:
>>> 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
>>>