【发布时间】:2021-02-26 06:38:50
【问题描述】:
例如: 如果我有 2 个列表,
list1 = ["apple","banana","pear"]
list2 = ["Tasty apple treat", "Amazing banana snack", "Best pear soup"]
我想检查 list1 中的每个字符串是否出现 in list2 中的任何项目。 所以在这个例子中,它会得到 True 作为回报。 但是如果 list2 看起来像这样......
list2 = ["Tasty apple treat", "Best pear soup", "Delicious grape pie"]
...它会返回 false,因为“香蕉”没有出现在列表中的任何项目中。
我尝试创建一个包含 True 和 False 值的 tfList,然后我可以检查 tfList 中的任何项目是否为假。
tfList = []
for x in list1:
if (x in list2):
tfList.append(True)
else:
tfList.append(False)
我也试过这个,但它可能是一个更糟糕的尝试:
if all(True if (x in list2) else False for x in list1):
第一个返回所有 False 值,第二个没有将 if 语句作为 true 运行,而是运行 else,即使我像第一个示例一样使用了测试列表。
**如果我的尝试看起来很疯狂,我对此很抱歉。
【问题讨论】: