How to check subsequence exists in a list? [duplicate]

空扰寡人 提交于 2019-12-11 03:22:11

问题


In python, it's possible to use the is keyword to check for contains, e.g.

>>> 3 in [1,2,3,4,5]
True

But this doesn't yield the same output if it's checking whether a list of a single integer is inside the reference list [1,2,3,4,5]:

>>> [3] in [1,2,3,4,5]
False

Also, checking a subsequence in the reference list cannot be achieved with:

>>> [3,4,5] in [1,2,3,4,5]
False

Is there a way to have a function that checks for subsequence such that the following returns true? e.g. a function call x_in_y():

>>> x_in_y([3,4,5], [1,2,3,4,5])
True
>>> x_in_y([3], [1,2,3,4,5])
True
>>> x_in_y(3, [1,2,3,4,5])
True
>>> x_in_y([2,3], [1,2,3,4,5])
True
>>> x_in_y([2,4], [1,2,3,4,5])
False
>>> x_in_y([1,5], [1,2,3,4,5])
False

Maybe something from itertools or operator?

(Note, the input lists can be non-unique)


回答1:


x_in_y() can be implemented by slicing the original list and comparing the slices to the input list:

def x_in_y(query, base):
    try:
        l = len(query)
    except TypeError:
        l = 1
        query = type(base)((query,))

    for i in range(len(base)):
        if base[i:i+l] == query:
            return True
    return False

Change range to xrange if you are using Python2.




回答2:


Maybe something like this:

def x_in_y(search_list, my_list):
    return all([s in my_list for s in search_list])

provided the search_list is a list.



来源:https://stackoverflow.com/questions/33392219/how-to-check-subsequence-exists-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!