![](/img/trans.png)
[英]how to check if items in a list can be found as an item in another list
[英]How Can I Check if Every Item in a List Appears Within Any Items in Another List?
例如:如果我有 2 個列表,
list1 = ["apple","banana","pear"]
list2 = ["Tasty apple treat", "Amazing banana snack", "Best pear soup"]
我想檢查 list1 中的每個字符串是否出現在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,即使我像第一個示例一樣使用了測試列表。
**如果我的嘗試看起來很瘋狂,我對此很抱歉。
您想檢查list1
的每個字符串是否是list2
的至少一個元素的子字符串。
您的第一種方法總是返回False
的原因是因為您沒有檢查x
是否出現在list2
的每個元素中,而是檢查x
是否是list2
的元素。
您可以通過以下方式實現您的目標:
def appears_in(list1, list2):
for word in list1:
appears = False
for sentence in list2:
if word in sentence:
appears = True
break
if not appears:
return False
return True
這應該有效:
find = True
for word in list1:
auxFind = False
for phrase in list2:
if(word in phrase):
auxFind = True
if(not auxFind):
find = False
print(find)
它的作用是驗證 list1 中的每個單詞是否在 list2 上至少出現一次,如果找到則返回 True。
all(
any(
word1 in map(str.lower, word2.split())
for word2 in list2
)
for word1 in list1
)
根據您的輸入有多好,您可以將map(str.lower, word2.split())
替換為word2
。
也許這有幫助
list1 = ["apple","banana","pear"]
list2 = ["Tasty apple treat", "Amazing banana snack", "Best pear soup"]
#return true/false for presense of list1 in any of items in list2
tf_list = [i in x for i in list1 for x in list2]
# if all items in list1 in list2
tf_list_all = all([i in x for i in list1 for x in list2])
# if any of items of list1 is in list 2
tf_list_any = any([i in x for i in list1 for x in list2])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.