簡體   English   中英

Python 在函數中找不到元組中的字符串?

[英]Python in function not finding string in tuple?

def bestInvitation(first, second):
    yeah=tuple(zip(first, second))
    res=list(set.intersection(*map(set, yeah)))
    common=str(res)
    count=0
    for i in yeah:
        if common in i:
            count+=1
    return count

if __name__ == '__main__':
    print(bestInvitation(["fishing", "gardening", "swimming", "fishing"], 
                         ["hunting", "fishing", "fishing", "biting"]))

在上面的代碼中,第 6 行應該找到 4 對活動之間的公共元素的次數。 這個例子應該返回 4,因為釣魚是一個常見的元素,它出現了 4 次。 但是,它返回 0。我認為這是因為 common 不僅僅是一個字符串,而是一個字符串的列表,但我不知道如何將 res 變成一個字符串。 有什么建議嗎?

一個簡單的print語句使問題變得清晰:

...
for i in yeah:
    print(common, i)
    if common in i:
...

輸出:

['fishing'] ('fishing', 'hunting')
['fishing'] ('gardening', 'fishing')
['fishing'] ('swimming', 'fishing')
['fishing'] ('fishing', 'biting')

沒有搜索字符串中的元組的字符串:您搜索包含您的元組內的字符串列表的字符串圖像 由於元組中沒有這樣的實體,因此if語句在每次迭代時都會失敗。

修復您的數據處理——一行:

common=str(res[0])

現在您獲得了所需的4輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM