查找两个字符串之间的共同字符

新手上路,请多包涵

我正在尝试 使用 for 循环 打印来自两个不同用户输入的常用字母。 (我需要使用 for 循环来完成它。)我遇到了两个问题: 1. 我的声明“如果 char 不在输出中……”没有提取唯一值。 2. 输出给我的是单个字母的列表,而不是单个字符串。我尝试拆分输出但拆分遇到类型错误。

 wrd = 'one'
sec_wrd = 'toe'

def unique_letters(x):
    output =[]
    for char in x:
        if char not in output and char != " ":
            output.append(char)
    return output

final_output = (unique_letters(wrd) + unique_letters(sec_wrd))

print(sorted(final_output))

原文由 JMatth 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 665
2 个回答

您正在尝试执行 Set Intersection 。 Python 有 set.intersection 相同的方法。您可以将它用于您的用例:

 >>> word_1 = 'one'
>>> word_2 = 'toe'

#    v join the intersection of `set`s to get back the string
#    v                             v  No need to type-cast it to `set`.
#    v                             v  Python takes care of it
>>> ''.join(set(word_1).intersection(word_2))
'oe'

set 将返回字符串中的唯一字符。 set.intersection 方法将返回两个集合中共有的字符。


如果 for 循环对你来说是必须的,那么你可以使用 列表理解 作为:

 >>> unique_1 = [w for w in set(word_1) if w in word_2]
# OR
# >>> unique_2 = [w for w in set(word_2) if w in word_1]

>>> ''.join(unique_1)  # Or, ''.join(unique_2)
'oe'

上述结果也可以通过显式 for 循环实现:

 my_str = ''
for w in set(word_1):
    if w in word_2:
        my_str += w

# where `my_str` will hold `'oe'`

原文由 Moinuddin Quadri 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于这类问题,您最好使用集合:

 wrd = 'one'
sec_wrd = 'toe'
wrd = set(wrd)
sec_wrd = set(sec_wrd)

print(''.join(sorted(wrd.intersection(sec_wrd))))

原文由 match 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题