【问题标题】:Python::check if the list contains item and also the pattern at another listPython::检查列表是否包含项目以及另一个列表中的模式
【发布时间】:2018-04-20 01:29:20
【问题描述】:

假设我有这个列表:

mylist = [a, b, c, d]    
yes_i_have = [b,c]    
pattern_not_match = [c,b]

如何检查列表是否包含项目以及另一个列表中的模式??

【问题讨论】:

  • 您的预期输出是什么?
  • 布尔输出就可以了!
  • 是 [b,d] 匹配还是不匹配?
  • @XinHuang 我需要的 [b,d] 不匹配
  • 你怎么不知道如何检查列表是否包含给定的项目?这在网上有很好的记录。对于该模式,使用列表切片遍历列表的 2 元素切片。

标签: python python-3.x


【解决方案1】:

怎么样:

mylist = [1, 2, 3, 4]
yes = [2, 3]
no = [3, 2]
yes in mylist  # False
tuple(yes) in zip(mylist[:], mylist[1:])  # True
tuple(no) in zip(mylist[:], mylist[1:])   # False

编辑,作为一个函数:

def find(l, x):
    return tuple(x) in zip(*[l[i:] for i in range(len(x))])

find(mylist, yes)  # True
find(mylist, no)   # False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多