gpt4 book ai didi

python - 在 python 中使用 any 函数时,有没有办法查看找到了哪个列表项?

转载 作者:行者123 更新时间:2023-12-05 08:45:25 25 4
gpt4 key购买 nike

我有一个要在文本文件中查找的单词列表。现在我正在尝试使用 any 方法遍历文件中的行。它正确返回 TrueFalse,因此它工作正常。

但我的问题是是否有可能看到它找到了哪个词?我可以通过我的代码和文本看到找到了哪个单词,但如果可能的话,我想以某种方式在代码中使用它。

下面是我的意思的一个例子。如果任何单词在 line 中,此代码将返回 TrueFalse

list_of_words = ['apple', 'banana', 'lemon']

with open(file, 'r') as f:
lines = f.readlines()

for line in lines:
x = any(word in line for word in list_of_words)
print(x)

最佳答案

您可以使用 next 代替,使用 default 以防找不到元素。

x = next((word for word in list_of_words if word in line), None)
if x is not None:
...

如果 None 可以是列表中的一个元素,您可以使用一些专用的哨兵对象来代替,例如

not_in = object()
x = next((word for word in list_of_words if word in line), not_in)
if x is not not_in:
...

或者显式捕获 StopIteration 错误:

try:
x = next(word for word in list_of_words if word in line)
...
except StopIteration:
pass

请注意,所有这些方法只为您提供第一个 这样的元素,然后停止检查其余部分(就像any 那样);相反,如果您对所有 此类元素感兴趣,则应像其他答案一样使用列表理解。

关于python - 在 python 中使用 any 函数时,有没有办法查看找到了哪个列表项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72938473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com