查找两个字符串之间的常见字符 [英] Find common characters between two strings
问题描述
我正在尝试使用for
循环从两个不同的用户输入中打印常用字母. (我需要使用for循环来完成此操作.)我遇到了两个问题:1.我的语句"If char not in output ..."没有提取唯一值. 2.输出为我提供了单个字母列表,而不是单个字符串.我尝试了分割输出,但是分割遇到了类型错误.
I am trying to print the common letters from two different user inputs using a for
loop. (I need to do it using a for loop.) I am running into two problems: 1. My statement "If char not in output..." is not pulling unique values. 2. The output is giving me a list of individual letters rather than a single string. I tried the split the output but split ran into a type error.
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
方法相同.您可以按以下方式将其用于您的用例:
You are trying to perform the Set Intersection. Python has set.intersection
method for the same. You can use it for your use-case as:
>>> 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
方法将返回两个集合中的共同字符.
set
will return the unique characters in your string. set.intersection
method will return the characters which are common in both the sets.
如果必须使用for
循环,那么您可以使用列表理解:
If for
loop is must for you, then you may use a list comprehension as:
>>> 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
循环来实现:
Above result could also be achieved with explicit for
loop as:
my_str = ''
for w in set(word_1):
if w in word_2:
my_str += w
# where `my_str` will hold `'oe'`
这篇关于查找两个字符串之间的常见字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!