python - 用户输入中使用了数组 A 和数组 B 中的多少个单词?

标签 python arrays python-3.x if-statement

这是一个我需要帮助的程序

   A = ["having", "had", "is"]
   B = ["will", "would", "should"]

   sentence = input("Enter a sentence") #E.g. 'I will be having it in the future'

   if A in sentence:
      ...

   elif B in sentence:
      ...

这里我需要知道句子中使用了数组 A 和数组 B 中的多少个单词。

这里的输出应该是:
句子中有1个A词和1个B词

你能帮帮我吗?

最佳答案

一个相当有效的方法是将 AB 和句子放入集合中并找到它们的交集的长度。例如:

A = set(["having", "had", "is"])
B = set(["will", "would", "should"])

sentence = 'I will be having it in the future'
S = set(sentence.split())

A_words = A.intersection(S)
B_words = B.intersection(S)

print(f'There is {len(A_words)} word from A and {len(B_words)} word from B in the sentence')

输出:

There is 1 word from A and 1 word from B in the sentence

关于python - 用户输入中使用了数组 A 和数组 B 中的多少个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62607497/

相关文章:

python - 存储在列表中的特定序列

python - pip install 给我这个错误 "can' t 打开文件 'pip' : [Errno 2] No such file or directory"

android - 如何关闭 Android 应用程序中打开的 HTML 文档?

javascript - 将类数组对象转换为数组的最佳方法?

java - 这里不允许使用数组初始值设定项

python - 在 flask 中不返回任何内容,但我不明白为什么

python - 如何获得用户权限?

javascript - 如何将表单转换为数组键值

python - 如何创建赋予提到的用户角色的机器人命令 |不和谐.py

python-3.x - 在 AWS Lambda Python 函数中解析 CloudWatch 警报