我正在尝试查找第一个字符串中也存在于第二个字符串中的字符数。这是我目前所拥有的:
def main():
text1 = raw_input("Enter word 1: ")
text2 = raw_input("Enter word 2: ")
print("The number of characters that occur in both", text1, "and", text2, "is", count)
def count(text1, text2):
char = 0
for i in text1:
for j in text2:
if i == j:
char += 1
return char
main()
我在 def count() 上遇到了问题。我不确定如何计算 text1 和 text2 中出现的不会重复的字母数量。感谢您的帮助!
最佳答案
使用set.intersection :
(set(text1).intersection(item2))
In [22]: len(set("bana").intersection("banana"))
Out[22]: 3
intersection() 将接受任何可迭代对象作为参数。
def count(text1, text2):
return len(set(text1).intersection(text2))
In [24]: count("foo","foobar")
Out[24]: 2
如果你想要重复:
def count(text1, text2):
s = set(text2)
return len([x for x in text1 if x in s])
In [29]: count("foo","foobar")
Out[29]: 3
In [30]: count("bana","banana")
Out[30]: 4
关于Python - 查找同时在 string1 和 string2 中找到的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25071675/