python - 在python中挑选包含特定单词的短语
问题描述
我有一个包含 10 个名称的列表和一个包含许多短语的列表。我只想选择包含其中一个名称的短语。
ArrayNames = [Mark, Alice, Paul]
ArrayPhrases = ["today is sunny", "Paul likes apples", "The cat is alive"]
在示例中,考虑到包含 Paul 的脸,给定这两个数组,有没有办法只选择第二个短语?这是我尝试过的:
def foo(x,y):
tmp = []
for phrase in x:
if any(y) in phrase:
tmp.append(phrase)
print(tmp)
x 是短语数组,y 是名称数组。这是输出:
if any(y) in phrase:
TypeError: coercing to Unicode: need string or buffer, bool found
我非常不确定我使用的关于 any() 构造的语法。有什么建议么?
解决方案
您对any的使用不正确,请执行以下操作:
ArrayNames = ['Mark', 'Alice', 'Paul']
ArrayPhrases = ["today is sunny", "Paul likes apples", "The cat is alive"]
result = []
for phrase in ArrayPhrases:
if any(name in phrase for name in ArrayNames):
result.append(phrase)
print(result)
输出
['Paul likes apples']
你得到一个TypeErrorif any(y) in phrase:
因为 any 返回一个 bool 并且你试图在一个字符串 ( )中搜索一个 bool 。
请注意,这是any(y)
有效的,因为它将使用每个字符串的真y
值。
推荐阅读
- rest - 使用 REST API 或 CURL 请求从特定 Jenkins 项目中删除/删除用户
- image-processing - matlab中的图像恢复质量(PSNR)
- monitoring - 触发比较 Zabbix 中的两个值
- keras - 如何在 keras 的预训练模型中插入自定义层
- docker - 无法在浏览器中打开 VS Code devcontainer
- javascript - Javascript:如何显示数组中的一定数量的项目并在按钮单击时显示其他项目?
- docker - 无法容器化 NestJS 微服务
- php - 安装 PHP 扩展 xml
- ruby-on-rails - 如何在 Rails 中保存对象之前验证实例化和验证子级
- c# - 如何在 C# WPF 中使用参数绘制圆弧?