如何使用数组更正此循环

2024-06-02 11:42:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如果标题中提到数组中的任何关键字,请不要单击标题。如果标题没有提到任何关键字,请单击标题。你知道吗

现在它一直点击,我知道为什么,但我不知道如何修复它。它总是单击,因为它遍历整个数组,最终有一个关键字不在标题中。思想?你知道吗

arr = ["bunny", "watch", "book"]

title = ("The book of coding. (e-book) by Seb Tota").lower()
length = len(arr)
for i in range(0,length - 1):
    if arr[i] in title:
        print "dont click"
    else:
        print "click"

这不应该单击标题,因为arr[2]在标题中


Tags: ofthein标题title关键字数组length
2条回答

在不需要索引变量时使用它们是不和谐的。这里不需要range。(顺便说一下,stop参数是您不想要的第一个数字,就像一个列表片段一样。)

arr = ["bunny", "watch", "book"]

title = ("The book of coding. (e-book) by Seb Tota").lower()
for s in arr:
    if s in title:
        print "dont click"
        break
else:
    print "click"

当您搜索第一个答案时,Python允许在for循环中使用else子句,但当您没有中断循环时,仍然需要一个默认值。但这个“发现第一”模式实际上可以在一行中实现。你知道吗

print next(("dont click" for s in arr if s in title), "click")

如果您只想打印或不打印整个数组,可以使用any来理解:

if any(word in title for word in arr):
    print("dont click")
else:
    print("click")

事实上,代码读起来就像你对问题的描述:

If any keyword from an array is mentioned in the title

相关问题 更多 >