【问题标题】:How to find out if certain values are contained in a list, order matters [duplicate]如何找出列表中是否包含某些值,顺序很重要[重复]
【发布时间】:2018-07-19 17:09:15
【问题描述】:
a = [1,1,0,0,0,'yes',1,1,0]

b = [1,1,0,0,0,'yes',0,1,1]

pattern = ['yes',1,1] #主列表a和b应该以相同的顺序检查模式

我期待这样的输出:

a 中的模式应该给出“是”或“真”

b 中的模式 - 应该给出 'No' 或 False

合并列表中的值以形成 1 个字符串并使用 if - in 条件进行检查不是我正在寻找的路径。

【问题讨论】:

标签: python python-3.x list


【解决方案1】:

您可以将any 与生成器理解和列表切片一起使用:

a = [1,1,0,0,0,'yes',1,1,0]
b = [1,1,0,0,0,'yes',0,1,1]
pattern = ['yes',1,1]

def comparer(L, p):
    n = len(p)
    return any(L[i:i+n] == p for i in range(len(L)-n))

comparer(a, pattern)  # True
comparer(b, pattern)  # False

【讨论】:

  • 哦!这完美地工作。谢谢您的帮助。我真的很感激!
  • @nisha21_m 也与其他答案不同,这也将保持type 的完整性。
【解决方案2】:
>>> a = [1,1,0,0,0,'yes',1,1,0]
>>> b = [1,1,0,0,0,'yes',0,1,1]
>>> pattern = ['yes',1,1]
>>> 
>>> tuple(pattern) in zip(*[a[i:] for i in range(len(pattern))])
True
>>> 
>>> tuple(pattern) in zip(*[b[i:] for i in range(len(pattern))])
False
>>> 

【讨论】:

  • 无需创建中介列表:tuple(pattern) in zip(*(a[i:] for i in range(len(pattern)))).
猜你喜欢
  • 2012-11-15
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 2018-04-25
  • 2011-10-07
相关资源
最近更新 更多