我正在尝试使用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))
请您参考如下方法:
您正在尝试执行 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'`
