我正在尝试 使用 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 许可协议
您正在尝试执行 Set Intersection 。 Python 有
set.intersection
相同的方法。您可以将它用于您的用例:set
将返回字符串中的唯一字符。set.intersection
方法将返回两个集合中共有的字符。如果
for
循环对你来说是必须的,那么你可以使用 列表理解 作为:上述结果也可以通过显式
for
循环实现: