使用any()函数的Python过滤数组

问题描述 投票:0回答:2

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

  • 客户准备花费的最大金额。
  • 由所有所需属性(“恐怖”,“科幻”,“浪漫”,“幻想”)的首字母组成的字符串。

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

我已经成功创建了一个过滤器,可以过滤出超出客户最高费用的图书。但是,该功能会继续输出用户提供的类别中属于[[any的所有书籍,而不是符合要求的满足所有类别的书籍(例如,幻想和浪漫的书籍,例如)。我试图用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本的恐怖和奇幻书籍的数组,因此该过滤器似乎不是工作正常。
python arrays any
2个回答
1
投票
在评论后编辑我的答案:

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

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)中

这将产生您想要的输出。


0
投票
这应该做:

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 (cat in cats for cat in cats_f))]

© www.soinside.com 2019 - 2024. All rights reserved.