比较两个字符串中单词的位置



我有一个任务:比较两个输入字符串的位置(字符串表示为List或Linked List(。我使用的是Python 3.9.5

例如:

A=[‘I’,‘am’,‘A’,‘good’,‘student’]

B=[‘I’,‘am’,‘student’]

=>匹配3/5

我试过很多方法,但都不对。

请帮帮我。谢谢

两种方法一种使用集合交集,另一种使用列表理解:

A = ['I', 'am', 'a', 'good', 'student']
B = ['I', 'am', 'student']
print(f"matches: {len(set(A).intersection(set(B)))}/{len(A)}") # or len(set(A)&set(B))
print(f"matches: {sum([1 for x in A if x in B])}/{len(A)}")
A = ['I', 'am', 'a', 'good', 'student']
B = ['I', 'am', 'student']
point=0
for value in B:
if value in A:
point+=1
print(" Matches: ",point,"/",len(A))

最新更新