如何在列表python中找到连续重复元素的索引范围?

如何在列表python中找到连续重复元素的索引范围?,python,list,Python,List,我正在处理一个列表列表,我想要列表的索引,元素从那里开始复制。给定列表已按每个子列表的第二个键值降序排序 在 我希望程序反映两个索引范围 1. 0 to 1 for 89 at 0th and 1st sublist 2. 2 to 4 for 64 at 2nd, 3rd and 4th sublist 如何做到这一点 我尝试循环,因为列表已排序: for i in range(0,len(A)-1): if A[i][1] == A[i+1][1]: print(i

我正在处理一个列表列表,我想要列表的索引,元素从那里开始复制。给定列表已按每个子列表的第二个键值降序排序 在

我希望程序反映两个索引范围

1. 0 to 1 for 89 at 0th and 1st sublist
2. 2 to 4 for 64 at 2nd, 3rd and 4th sublist
如何做到这一点

我尝试循环,因为列表已排序:

for i in range(0,len(A)-1):
    if A[i][1] == A[i+1][1]:
        print(i)

但是它只返回起始索引,而不是结束索引。

您可以使用
collections.defaultdict
创建具有
set
值的字典。迭代子列表和每个子列表中的项目,可以向每个集合添加索引:

A = [[11, 89, 9], [12, 89, 48], [13, 64, 44], [22, 64, 56], [33, 64, 9]]

from collections import defaultdict

d = defaultdict(set)

for idx, sublist in enumerate(A):
    for value in sublist:
        d[value].add(idx)

print(d)

defaultdict(set,
            {11: {0}, 89: {0, 1}, 9: {0, 4}, 12: {1},
             48: {1}, 13: {2}, 64: {2, 3, 4},
             44: {2}, 22: {3}, 56: {3}, 33: {4}})

以下是解决您问题的另一个解决方案:

def rank(pos):
    return {1:"1st", 2:"2nd", 3:"3rd"}.get(pos, str(pos)+"th")

A = [[11, 89, 9], [12, 89, 48], [13, 64, 44], [22, 64, 56], [33, 64, 9]]

#Take every second element from each sublist.
B = [elem[1] for elem in A]

#Find all indices of those elements.
indices = [[elem, B.index(elem), B.index(elem) + B.count(elem)-1, [i for i in range(B.index(elem), B.index(elem) + B.count(elem))]] for elem in sorted(set(B), reverse=True)]

#Print formatted results.
for i in range(len(indices)):
    print("%d. " % (i+1), end="")
    print("%d to %d for %d at" % (indices[i][1],indices[i][2],indices[i][0]), end=" ")
    print(", ".join([rank(position) for position in indices[i][3][:-1]]), end=" ")
    print("and %s." % (rank(indices[i][3][-1])))
输出:

1. 0 to 1 for 89 at 0th and 1st.
2. 2 to 4 for 64 at 2nd, 3rd and 4th.
用于分隔组,然后保留包含多个项目的组

import itertools
# generator to produce the first item in each *sub-list*.
b = (item[1] for item in a)

where = 0    # need this to keep track of original indices
for key, group in itertools.groupby(b):
    length = sum(1 for item in group)
    #length = len([*group])
    if length > 1:
        items = [where + i for i in range(length)]
        print(f'{key}:{items}')
        #print('{}:{}'.format(key, items))
    where += length
结果

89:[0, 1]
64:[2, 3, 4]

如果有人想将问题标记为重复,我将删除我的答案:重复/变体



您只关心内部列表中的第一项吗?
89:[0, 1]
64:[2, 3, 4]