在python中搜索多维列表

问题描述 投票:-1回答:4

编辑。我有一个三维集,即F = [(1,2,1), (2,3,0), (1,2,4)]

如果要检查(1,2,1)中是否存在F,请使用F.__contains__((1,2,1))

但是如何检查列表中是否存在(1,2,just any number)(1,just any number,just any number)

我使用了F.__contains__((1,2,True)),但无法正常工作。

python list contains
4个回答
0
投票

在评论中,穆罕默德要求一种更通用的搜索方法。这是一种方法。

from itertools import zip_longest

F = [(1,2,1), (2,3,0), (1,2,4)]

def search_2d_list(needle, haystack):
    def equal_or_none(row):
        return all(q is None or q == i for q, i in zip_longest(needle, row))
    return any(equal_or_none(row) for row in haystack)

终端结果

>>> search_2d_list((1,), F)
True
>>> search_2d_list((1,2), F)
True
>>> search_2d_list((1,2,1), F)
True
>>> search_2d_list((1,2,3), F)
False
>>> search_2d_list((2,2,3), F)
False
>>> search_2d_list((2,2), F)
False
>>> search_2d_list((2,None,2), F)
False
>>> search_2d_list((2,None,0), F)
True

1
投票
>>> T = (1, 2)
>>> F = [(1,2,1), (2,3,0), (1,2,4)]
>>> any(filter(lambda x:x[:2]==T, F))
True

0
投票

[不要直接使用特殊方法__contains__,如此处其他人所提到的。使用执行相同任务的成员运算符in

代码

F = [(1,2,1), (2,3,0), (1,2,4)]

print((1, 2) in [element[:2] for element in F])  # True

-1
投票
(1, 2) in [x[:-1] for x in F]

已注释的注释请不要直接使用包含

© www.soinside.com 2019 - 2024. All rights reserved.