Py学习  »  Python

程序输出错误-返回两个字符串中的单词(python)

skepticalforever • 4 年前 • 305 次点击  
def words_in_both(string1, string2):
    s = set()
    res = []
    for word in string1.lower().split():
        if word not in s: s.add(word)
    for word in string2.lower().split():
        if word in s: res.append(word)
    return res

print(words_in_both("Here is my MY test1","Here IS My MY mY test2"))

我在代码中遇到错误,我试图只返回两个字符串中的单词,而不考虑大小写,但是当我运行代码时,我返回的是:['here'、'is'、'my'、'my'、'my']

有人能帮我找出我的问题吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50103
 
305 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Marsilinou Zaky
Reply   •   1 楼
Marsilinou Zaky    4 年前

您可以分析要设置的结果,然后返回列表以避免重复

def words_in_both(string1, string2):
    s = set()
    res = []
    for word in string1.lower().split():
        if word not in s: s.add(word)
    for word in string2.lower().split():
        if word in s: res.append(word)
    return list(set(res))

print(words_in_both("Here is my MY test1","Here IS My MY mY test2"))

输出: ['here', 'is', 'my']

PL200
Reply   •   2 楼
PL200    4 年前

您的工具确实返回了两个字符串中的单词,但是您没有考虑到这些单词可能出现多次。如果你想要一个唯一的列表,你应该先转换到一个集合,然后再返回到一个列表。

参考代码如下:

def words_in_both(string1, string2):
    s = set()
    res = []
    for word in string1.lower().split():
        if word not in s: s.add(word)
    for word in string2.lower().split():
        if word in s: res.append(word)
    return list(set(res)) #Changed line

print(words_in_both("Here is my MY test1","Here IS My MY mY test2"))