python - 使用 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 部恐怖和奇幻书籍的数组,因此过滤器似乎无法正常工作.
解决方案
在您发表评论后编辑我的答案:
您在过滤中的第二个条件应该是:
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
)中
这会产生您想要的输出。
推荐阅读
- angular - ng-bootstrap 模态中的组件
- sql - 在 3 个字符后插入空格 (SQL Express)
- php - WooCommerce+WP-All-Import - 在链接的 csv 文本中显示股票价值
- ios - 当重复设置为“是”时,UNUserNotification 不会从待处理通知中删除 - Swift
- mongoose - $and not working in $or 意味着 $or 部分不工作
- java - Hibernate 和 SQL Server - Java 和具有 Java 8 类型的数据库之间的时间不匹配
- php - Centos 7.5 中忽略了内存限制
- reactjs - React Native 中的 this.props undefined: TypeError: Cannot read property 'title' of undefined
- sonarlint-vs - Sonarlint 在 Visual Studio 代码中不起作用
- angular - 如何在primeng文件上传时显示maxFileSize消息?