查找列表列表中项目的部分匹配

时间:2014-12-22 17:34:40

标签: python

我有这样的列表列表:

l = [["08:00", "09:00", 60, False, 1.0],
     ["09:00", "10:00", 60, False, 0.3],
     ["12:00", "13:00", 60, False, 2.0],]

我想检查列表l是否有元素,但我不知道最后 float 的值。我只知道["12:00", "13:00", 60, False, ]

if ["12:00", "13:00", 60, False, ???? ] in l:
    pass

你有什么想法吗?

2 个答案:

答案 0 :(得分:6)

您可以创建一个比较等于所有内容的虚拟类。然后,您可以将其用作in条件中的一种通配符。

class Dummy:
    def __eq__(self, other):
        return True

l = [["08:00", "09:00", 60, False, 1.0],
     ["09:00", "10:00", 60, False, 0.3],
     ["12:00", "13:00", 60, False, 2.0],]

if ["12:00", "13:00", 60, False, Dummy() ] in l:
    print "found"

答案 1 :(得分:0)

我这样做:

# The input.
l = [["08:00", "09:00", 60, False, 1.0],
     ["09:00", "10:00", 60, False, 0.3],
     ["12:00", "13:00", 60, False, 2.0],]

# The pattern you want to match.
pattern = ["12:00", "13:00", 60, False]

# Make a list of all comparisons.
result = [pattern == e[:4] for e in l]

# Test.
if any(result):
    pass