首页 > 解决方案 > 使用 any() 函数的 Python 过滤数组

问题描述

我正在尝试编写一个通过两个输入来推荐书籍的程序:

所需的属性输入应该是字符串,例如 sh 或 shf(顺序无关紧要,因此字符串“shf”被视为与“fhs”相同)。

我已经成功创建了一个过滤器,可以过滤掉超出客户最大成本的书籍。但是,该功能继续输出用户提供的任何类别中的任何书籍,而不是根据需要满足所有类别的书籍(例如,同时具有幻想和浪漫的书籍)。我试图用any()函数替换all()函数,但这似乎并不能解决问题。谁能提供关于我哪里出错的建议?

def recommend_books(max_price, cats):
    if not set(cats).issubset(set(book_categories)):
        raise ValueError(f'{cats} contains an invalid category code')
    cats_f = [cat for cat_i, cat in book_categories.items() if cat_i in set(cats)]
    return [book for book, price, cats in book_data
            if (price <= max_price and all(True for cat in cats if cat in cats_f))]


book_data = [["Harry Potter", 8, ["fantasy", "romance"]],
             ["IT", 11, ["horror", "fantasy"]],
             ["Star Wars", 22, ["scifi", "romance", "fantasy"]],
             ["Carrie", 13, ["horror"]],
             ["Lord of the Rings", 29, ["fantasy", "romance"]]
             ]

book = [book[0] for book in book_data]

book_categories = {}
for book, price, category in book_data:
    for cat in category:
        cat_initial = cat[0]
        if not cat_initial in book_categories:
            book_categories[cat_initial] = cat

recommend_books(25, "hf")
# Output should be an array of the Titles of the suitable book recommendations
# I.e. ["IT"]

此示例的输出为:['Harry Potter', 'IT', 'Star Wars', 'Carrie'] 这是一个包含所有少于 25 部恐怖和奇幻书籍的数组,因此过滤器似乎无法正常工作.

标签: pythonarraysany

解决方案


在您发表评论后编辑我的答案:

您在过滤中的第二个条件应该是:

all(elem in cats for elem in cats_f)

和完整的功能:

def recommend_books(max_price, cats):
        if not set(cats).issubset(set(book_categories)):
            raise ValueError(f'{cats} contains an invalid category code')
        cats_f = [cat for cat_i, cat in book_categories.items() if cat_i in set(cats)]
        return [book for book, price, cats in book_data 
                if (price <= max_price and **all (True for cat in cats if cat in cats_f))**]

遍历cat_f您想要拥有的所有类别(),并检查它们是否都在书的类别(cats)中

这会产生您想要的输出。


推荐阅读