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)

I have this code. What I want to do is to print out the indexes of each element so its in the form [('123',[0,3,5]),('231',[1]),('34',[2,4])] however my code produces [('123',[3,5]),('34',[4])] Is there anyway I can edit my code so it produces the answer I want without changing the form of the array so the output will stay as [('123',[0,3,5]),('231',[1]),('34',[2,4])]

1
  • 234 is not in your list 'this' and you have '' around your list Commented Apr 27, 2013 at 14:34

1 Answer 1

3

Something like this:

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])]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.