在列表中查找连续的项目

find consecutive items in list

列表如下:

list = ["A","B","C","D","E","F","G","H","I"]

Python中如何获取first元素的index此列表中的一个子列表(连续项目)。

子列表的大小不一。

子列表的示例是:

 ["C","D","E"],["B","C","D","E","F","G"],["G","H"], ...

您可以使用以下内容,假设 listsub_lists 有效:

def isSublist(entire_list, sub_list):
    return sub_list in [entire_list[i:len(sub_list)+i] for i in range(len(entire_list) - len(sub_list))]


all_list = ["A","B","C","D","E","F","G","H","I"]
sub_lists = [["C","D","E"],["B","C","D","E","F","G"],["G","H"],["B", "D"], ["E"], ["E", "F", "H"]]

res = [all_list.index(l[0]) for l in sub_lists if isSublist(all_list, l)]
print(res)

它使用列表理解,您可以在下面阅读更多内容 link:

https://realpython.com/list-comprehension-python/