要一直走下去

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

查找list中重复项及索引

def get_group_dict(distinct_list, offset=0):
    '''
    找出列表中所有相同的项及索引
    :param distinct_list: 给定的有重复项的列表
    :param offset: 偏移量即索引起始值
    :return: {'重复项',[索引1,索引2...],}
    '''
    temps = []       # 临时列表
    group_dict = {}  # 运行结果:分组及序号
    for index, item in enumerate(distinct_list, offset):
        if item in temps:
            if item in group_dict:
                group_dict[item].append(index)
            else:
                group_dict[item] = [distinct_list.index(item) + offset]
                group_dict[item].append(index)
        temps.append(item)
        index += 1
    return group_dict

if __name__ == '__main__':
    '''
    b:2,7,12,23
    c:3,4,5,11,17
    f:9,14,19
    '''
    #     1    2    3    4    5   6    7    8    9    10   11   12   13   14   15   16   17   18   19   20
    distinct_list = ['a','c','a','b']  # 21 22 23
    print(get_group_dict(distinct_list, offset=1))

 迭代器显示索引:可以把两个迭代器用zip函数合并

zp = zip(range(0, 5), range(2, 20))
for index, name in zp:
    print(index, name)
'''
0 2
1 3
2 4
3 5
4 6
'''

 

posted on 2019-04-25 15:03  要一直走下去  阅读(804)  评论(0编辑  收藏  举报