为什么在 Python 协程中未检测到第二个参数?

Why is second argument not detected in Python Coroutines?

我修改了Coroutines的一些代码如下:

def grep(p1, p2):
    print("Searching for", p1 ,"and", p2)
    while True:
        line = (yield)
        if (p1 or p2) in line:
            print(line)

search = grep('love', 'woman')
next(search)
search.send("I love you")
search.send("Don't you love me?")
search.send("I love coroutines instead!")   
search.send("Beatiful woman")

输出:

Searching for love and woman
I love you
Don't you love me?
I love coroutines instead!

第二个参数 "woman" 在上次搜索中未被识别。这是为什么?

你的情况应该是这样的:

if p1 in line or p2 in line:

因为 (p1 or p2) 会 return p1 只要里面有东西。
所以你当前的条件总是评估为 if p1 in line:

因为您的代码条件是两个参数(p1 或 p2)之一匹配它 return 只有 p1 这就是它不 return 最后发送函数结果的原因。 现在试试这段代码。

另外附上代码输出截图。

 def grep(p1, p2):
        print("Searching for", p1 ,"and", p2)
        while True:
            line = (yield)
            if (p1) in line:
                print(line)
            if (p2) in line:
                print(line)

    search = grep('love', 'woman')
    next(search)
    search.send("I love you")
    search.send("Don't you love me?")
    search.send("I love coroutines instead!")   
    search.send("beautiful woman")