【问题标题】:Comparing two strings for multiple outcomes比较两个字符串以获得多个结果
【发布时间】:2021-02-22 10:10:08
【问题描述】:

你会得到两个句子S1,S2你的任务是找到

  • 一个。 S1、S2之间的常用词数
  • 乙。在 S1 中但不在 S2 中的单词
  • c。在 S2 中但不在 S1 中的单词

我似乎无法为单词做这个问题,但我可以为字母做这个问题。请帮帮我

例子

S1= "the first column F will contain only 5 unique values"
S2= "the second column S will contain only 3 unique values"

输出:

a. 7
b. ['first','F','5']
c. ['second','S','3']

【问题讨论】:

标签: python-3.x string list


【解决方案1】:

使用集合。

a_words = set(S1.split(" "))
b_words = set(S2.split(" "))

A_ANS = len(a_words.intersection(b_words))
B_ANS = list(a_words - b_words)
C_ANS = list(b_words - a_words)

【讨论】:

  • 我尝试运行代码,结果发生了“TypeError: unhashable type: 'list'
  • def string_features(S1, S2): a_words = {S1.split(" ")} b_words = {S2.split(" ")} a = len(a_words.intersections(b_words)) b = list(a_words - b_words) c = list(b_words - a_words) return a,b,c S1=“第一列 F 将仅包含 5 个唯一值” S2=“第二列 S 将仅包含 3 个唯一值”a ,b,c = string_features(S1, S2) print(a) print(b) print(c)
  • 我改了一点代码,请重试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 2017-07-18
相关资源
最近更新 更多