[英]Python - Find a list within a list of lists
我有一個列表列表,其中每個列表都可以是任意長度,例如:
list_of_lists = [[2, 2, 2, 3], [2, 3, 4], [2, 2, 6]]
我需要一種在列表列表中搜索特定列表的方法。 例如,一個contains()
函數將在下面返回True
:
list_of_lists.contains([2, 2, 6])
我已經看到了可以將“內部列表”轉換為元組的答案,但這對我沒有幫助。 是否有一個具有此功能的庫?
in
使用:
list_of_lists = [[2,2,2,3],[2,3,4],[2,2,6]]
if [2,2,6] in list_of_lists:
print("found")
else:
print("not found")
輸出 :
found
同樣,假設嵌套列表中的最后一個列表為: [2, 2, 6, 8]
list_of_lists = [[2,2,2,3],[2,3,4],[2,2,6,8]]
if [2,2,6] in list_of_lists:
print("found")
else:
print("not found")
輸出 :
not found
編輯 :
在此期間,如果您想為列表的存在提供布爾值:
def chkList(lst):
return True if lst in list_of_lists else False
list_of_lists = [[2,2,2,3],[2,3,4],[2,2,6]]
print(chkList([2,2,6]))
輸出 :
True
使用in
:
print([2,2,6] in list_of_lists)
或使用
__contains__
:
print(list_of_lists.__contains__([2,2,6]))
(請勿使用__contains__
,高度不推薦)
建議in
或==
使用多個答案,以查看列表是否包含元素(另一個列表)。
但是,如果您不關心要比較的列表中元素的順序,則可以采用以下解決方案。
import collections
# 'list_' is the list we are searching for in a bigger list 'list_of_lists'
for element in list_of_lists:
if collections.Counter(element) == collections.Counter(list_) :
return True
以上解決方案要求元素是可哈希的。
如果發現collections
太復雜而難以理解,則可以簡單地使用set(list_) == set(element)
。
以上方法要求元素是可哈希的。 如果元素不可哈希但可排序,則可以使用sorted(list_)==sorted(element)
。
如果您喜歡做些什么
if any(list == [2, 2, 6] for list in list_of_lists):
#execute whatever code you want for this case
萬一您需要一個更通用的解決方案,以檢查您的目標列表是否實際上是內部列表之一的有序子列表。 技巧是將列表轉換為允許有效子字符串檢查的字符串表示形式。
>>> list_of_lists = [[2,2,2,3],[2,3,4],[2,2,6,8]]
>>> serialize = lambda x: ','.join(map(str,x))
>>> any(serialize([2,2,6]) in serialize(item) for item in list_of_lists)
True
>>> any(serialize([2,2,7]) in serialize(item) for item in list_of_lists)
False
請從ipython檢查以下代碼
In [18]: list
Out[18]: [[1, 2, 3], [4, 5, 6], [3, 2, 4]]
In [19]: def contains(sublist):
if sublist in list:
return True
else:
return False
....:
In [20]: contains([1,2,3])
True
In [21]: contains(2)
False
In [22]:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.