有没有办法过滤这样的列表?
movies = [
[["t", "transformers"],["g", "animation"],["d", "2005"]],
[["t", "ted"],["g", "comedy"],["d", "2008"]],
[["t", "starwars"],["g", "action"],["d", "2000"]]
]
有这样的过滤器列表
filter = [["g", "animation"], ["d", "2005"]]
并收到
["transformers"]
我认为由于电影列表的结构不可能,但我不知道Python向导是否有答案。
如果您对此有任何建议,谢谢。
答案 0 :(得分:1)
类似的东西:
movies = [
[["t", "transformers"],["g", "animation"],["d", "2005"]],
[["t", "ted"],["g", "comedy"],["d", "2008"]],
[["t", "starwars"],["g", "action"],["d", "2000"]]
]
fil = [["g", "animation"], ["d", "2005"]]
print [i[0][1] for i in movies if fil[0] in i and fil[1] in i]
这将打印:
['transformers']
答案 1 :(得分:1)
另一种方法是使用面向对象编程(OPP)。你可以实现一个非常简单的类,它将为你节省大量的工作。
class Movie:
def __init__(self, title, genre, year):
self.title = title
self.genre = genre
self.year = year
def filter(self, filter_):
""" filter_ here is a dict."""
for feature, value in filter_.items():
if getattr(self, feature) != value:
return False
return True
def __repr__(self):
return self.title
movies = [
Movie("transformers", "animation", 2005),
Movie("ted", "comedy", 2008),
Movie("starwars", "action", 2000)
]
filter_ = { "genre": "animation", "year": 2005}
movies = [movie for movie in movies if movie.filter(filter_)]
print(movies)
这产生了输出:
['transformers']
你也可以这样做:
print(movies[0].title)
将产生输出:
'transformers'
答案 2 :(得分:0)
第一步,在dicts中进行重组(我将filter
重命名为filtr
,因为filter
是内置函数):
movies = [dict(item) for item in movies]
filtr = dict(filtr)
然后,根据您的标准进行过滤:
filtered = [item for item in movies if all(item[k] == v for k,v in filtr.iteritems())]
在这里,您循环播放所有电影,然后查找与所有滤镜元素匹配的电影。
然后,您打印所有匹配的标题
print [item['t'] for item in filtered]
# ['transformers']