2
this = '['123','231','34','123','34','123']'
dups = collections.defaultdict(list)
for i, item in enumerate(this):
    for j, orig in enumerate(seen):
        if item == orig:
        dups[j].append(i)
        break

    else:
        seen.append(item)

我有这个代码。我想要做的是打印出每个元素的索引,以便它在表单[('123',[0,3,5]),('231',[1]),('34',[2,4])] 中但是我的代码产生[('123',[3,5]),('34',[4])] 无论如何我可以编辑我的代码,以便它产生我想要的答案而不改变数组的形式,所以输出将保持不变作为 [('123',[0,3,5]),('231',[1]),('34',[2,4])]

4

1 回答 1

3

像这样的东西:

In [35]: lis=['123','231','34','123','34','123']

In [36]: from collections import defaultdict

In [37]: dic=defaultdict(list)

In [38]: for i,x in enumerate(lis):
   ....:     dic[x].append(i)
   ....:     

In [40]: dic.items()
Out[40]: [('123', [0, 3, 5]), ('231', [1]), ('34', [2, 4])]
于 2013-04-27T14:35:11.843 回答