s =['Hello','World','Hello','World'] l = list() for x,y in enumerate(s): l.append((y,x)) The output I got is [('Hello', 0), ('World', 1), ('Hello', 2), ('World', 3)]
But I want
Hello-[0,2] World-[1,3] You can use a dictionary:
d = {} for i, v in enumerate(s): if v in d: d[v].append(i) else: d[v] = [i] d # {'Hello': [0, 2], 'World': [1, 3]} It seems like collections.defaultdict is a perfect fit for this case (see also the answer of @mhawke) :
from collections import defaultdict dd = defaultdict(list) for idx, item in enumerate(s): dd[item].append(idx) Then convert this to a plain dictionary again:
>>> dict(dd) {'Hello': [0, 2], 'World': [1, 3]} I recently created a package containing a function that could be used as alternative iteration_utilities.groupedby:
>>> from iteration_utilities import groupedby >>> from operator import itemgetter >>> s =['Hello','World','Hello','World'] >>> groupedby(enumerate(s), key=itemgetter(1), keep=itemgetter(0)) {'Hello': [0, 2], 'World': [1, 3]} Use a collections.defaultdict of lists:
from collections import defaultdict d = defaultdict(list) s = ['Hello','World','Hello','World'] for index, key in enumerate(s): d[key].append(index) >>> print(d) defaultdict(<type 'list'>, {'World': [1, 3], 'Hello': [0, 2]}) >>> print(dict(d)) # convert to a std dictionary {'World': [1, 3], 'Hello': [0, 2]} This can also be done using a fairly simple dictionary comprehension:
>>> s =['Hello','World','Hello','World'] >>> d = {k: [pos for pos, el in enumerate(s) if el == k] for k in set(s)} >>> d {'World': [1, 3], 'Hello': [0, 2]} >>> This works by making keys using each unique element in the list s(which set(s) does), and getting the index of each of the unique elements(which the list comprehension does).
dictcontaining{'Hello': [0, 2], 'World': [1, 3]}?