我想在列表中找到连续且相同的元素:
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
。我怎样才能做到这一点?
答案 0 :(得分:1)
这是一种基于generator的方法:
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)]]