Python:在另一个列表的成员中查找列表(顺序) [英] Python: find a list within members of another list(in order)

查看:125
本文介绍了Python:在另一个列表的成员中查找列表(顺序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这个:

a='abcdefghij'
b='de'

然后在a中找到b:

b in a => True

有没有办法对列表做类似的事情? 像这样:

Is there a way of doing an similar thing with lists? Like this:

a=list('abcdefghij')
b=list('de')

b in a => False 

假"结果是可以理解的-因为它正确地寻找元素"de",而不是(我恰好希望它做的)"d"后跟"e"

The 'False' result is understandable - because its rightly looking for an element 'de', rather than (what I happen to want it to do) 'd' followed by 'e'

这是可行的,我知道:

a=['a', 'b', 'c', ['d', 'e'], 'f', 'g', 'h']
b=list('de')
b in a => True

我可以处理数据以获得所需的内容-但是有没有一种简短的Python方式可以做到这一点?

I can crunch the data to get what I want - but is there a short Pythonic way of doing this?

为了澄清:我需要在这里保留顺序(b = ['e','d'],应返回False).

To clarify: I need to preserve ordering here (b=['e','d'], should return False).

如果有帮助,我所拥有的是一个列表列表:这些列表代表有向图中从节点1到节点x的所有可能路径(已访问节点的列表):我想分解"更长路径中的公共路径. (因此,寻找所有构成所有较长路径的不可约的原子"路径).

And if it helps, what I have is a list of lists: these lists represents all possible paths (a list of visited nodes) from node-1 to node-x in a directed graph: I want to 'factor' out common paths in any longer paths. (So looking for all irreducible 'atomic' paths which constituent all the longer paths).

推荐答案

不知道这是否是pythonic,但是我会这样:

Don't know if this is very pythonic, but I would do it in this way:

def is_sublist(a, b):
    if not a: return True
    if not b: return False
    return b[:len(a)] == a or is_sublist(a, b[1:])

讨论中提供了更短的解决方案 ,但是与set的解决方案一样存在相同的问题-它不考虑元素的顺序.

Shorter solution is offered in this discussion, but it suffers from the same problems as solutions with set - it doesn't consider order of elements.

更新:
受MAK的启发,我介绍了我的代码的更简洁明了的版本.

UPDATE:
Inspired by MAK I introduced more concise and clear version of my code.

更新: 由于切片中的列表复制,因此此方法存在性能问题.另外,由于它是递归的,因此您可能会遇到长列表的递归限制.要消除复制,您可以使用 Numpy 切片. org/NumPy_for_Matlab_Users"rel =" nofollow noreferrer>创建视图,而不是副本.如果遇到性能或递归限制问题,则应使用不递归的解决方案.

UPDATE: There are performance concerns about this method, due to list copying in slices. Also, as it is recursive, you can encounter recursion limit for long lists. To eliminate copying, you can use Numpy slices which creates views, not copies. If you encounter performance or recursion limit issues you should use solution without recursion.

这篇关于Python:在另一个列表的成员中查找列表(顺序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆