【问题标题】:Compare the position of the words in two strings比较两个字符串中单词的位置
【发布时间】:2021-05-28 12:42:15
【问题描述】:

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

例如:

A = ['我','我','a','好','学生']

B = ['我','我','学生']

=> 匹配 3/5

我尝试了很多方法,但都不正确。

请帮助我。谢谢

【问题讨论】:

  • 请发布您的尝试;有人可能会帮助您解决问题。
  • 这和linked-list有什么关系?
  • 如果有重复怎么办?为什么第二个数字是 5?
  • 如果 A 有单词不在 B 中并且 B 有单词不在 A 中怎么办?

标签: python-3.x list linked-list


【解决方案1】:

两种方式,一种使用集合交集,另一种使用列表推导:

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)}")

【讨论】:

    【解决方案2】:
    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))
    

    【讨论】:

      猜你喜欢
      • 2019-04-27
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 2021-05-09
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多