![](/img/trans.png)
[英]how to find if list elements are contained in other list without exact match
[英]How match contained sub string in four list?
我有很長的四個列表,我想檢查list_1中的一個單詞以及list_2中的那個單詞是否與另一個字符串(但該子字符串仍然存在)對於所有四個列表都是相同的,如果該子字符串在所有四個列表中均存在,則進行打印。
因此,假設我有以下四個列表:
a=["1","2","45","32","76"]
b=["5","8","345","32789","43"]
c=["362145","9932643","653"]
d=["194532","5423256","76"]
所以想匹配45
, 32
在列表中的和在表b也因為34
5包含34,但它也含有45 3 45
和32
789包含32和列表C包含3621 [45]
和99 [32]
643包含32和因此在列表d 19 [45]
32中包含45,而在542 [32]
56中包含32,因此如果子字符串(示例45)在所有4個列表中,則進行打印。
我嘗試了“ in”方法,但這種方法不起作用,然后又嘗試了set(),該方法也不起作用,該怎么辦?
PS:有沒有不遍歷整個列表的方法? 因為此模塊是大型程序的子模塊,並且該程序已經包含許多循環(如果可能的話,則可能沒有循環),否則歡迎所有建議:)
谷歌幫助了我。
使用any("45" in s for s in a)
來檢查數字是否在列表a中,依此類推。 如果找到它,則返回True
。
編輯:這是一個例子。
check = input("What number are you looking for?")
if any(check in s for s in a):
if any(check in s for s in b):
if any(check in s for s in c):
if any(check in s for s in d):
print("something")
就像您描述的那樣,它不可能避免循環,但是您可以使用理解列表。
例如:
a = ["1","2","45","32","76"]
b = ["5","8","345","32789","43"]
c = ["362145","9932643","653"]
d = ["194532","5423256","76"]
result = []
for x in a:
if (any(x in s for s in b) and
any(x in s for s in c) and
any(x in s for s in d)):
result.append(x)
每個any
使用迭代器來檢查項目x是否存在於列表b , c或d的任何字符串中。
可以使用列表理解來重寫此構造:
result = [x for x in a
if (any(x in s for s in b) and
any(x in s for s in c) and
any(x in s for s in d))]
print(result)
你得到:
['2', '45', '32']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.