Python 如何在嵌套列表中获取本地范围的项?

Python 如何在嵌套列表中获取本地范围的项?,python,list,Python,List,我试图在列表中找到连续且相同的元素: a = [1, 1, 1, 2, 3, 2, 2, 2, 1, 2, 3, 4, 1, 1, 1, 5, 5, 5] new_list_1 = [] new_list_2 = [] def hello(x): for j, i in enumerate(x): try: if x[j] == x[j + 1] or x[j] == x[j-1]: new_list_1.app

我试图在列表中找到连续且相同的元素:

a = [1, 1, 1, 2, 3, 2, 2, 2, 1, 2, 3, 4, 1, 1, 1, 5, 5, 5]

new_list_1 = []
new_list_2 = []

def hello(x):
    for j, i in enumerate(x):
        try:
            if x[j] == x[j + 1] or x[j] == x[j-1]:
                new_list_1.append((i, j))
            else:
                new_list_2.append((i, j))
        except IndexError:
            if x[j]==x[j-1]:
                new_list_1.append((i, j))

print(hello(a))
print(new_list_1)
它回来了:

[(1, 0), (1, 1), (1, 2), (2, 5), (2, 6), (2, 7), (1, 12), (1, 13), (1, 14), (5, 15), (5, 16), (5, 17)]
但我想要这样的东西:

[[(1, 0), (1, 1), (1, 2)], [(2, 5), (2, 6), (2, 7)], [(1, 12), (1, 13), (1, 14)], [(5, 15), (5, 16), (5, 17)]]
我不想使用任何外部模块,如itertools
chain
groupby
。如何实现这一点?

这是一种基于

def indexed_groups(lst):
    ret_val, crnt = [], None
    for i, x in enumerate(lst):
        if x != crnt:  # for every new item
            if len(ret_val) > 1:  # check if there is a group to yield
                yield ret_val
            ret_val, crnt = [], x  # reset group and current
        ret_val.append((x, i))  # collect (item, index) pairs
    if len(ret_val) > 1:  # check last group
        yield ret_val

>>> list(indexed_groups(a))
[[(1, 0), (1, 1), (1, 2)], 
 [(2, 5), (2, 6), (2, 7)], 
 [(1, 12), (1, 13), (1, 14)], 
 [(5, 15), (5, 16), (5, 17)]]

你能读一下我的最后一行吗?您可以对此进行向下投票。当然可以,将其编辑为无需任何导入即可工作;)为什么会有任意的模块限制?Itertools是标准库的一部分。“我不想使用任何外部模块,如Itertools链或groupby,我如何实现这一点?”-为什么不?这仅仅是为了练习吗?如何确定每个列表中有哪些对?