klabanus
klabanus

Reputation: 75

Find positon of words in list

I've got a list which looks like this:

listWords = ['foo', 'bar', 'foobar', 'foo', 'bar']

Then I would like to use enumerate over the list, to get the word positions, but the output should look like this:

foo [0,3]
bar [1,4]
foobar [2]

I was thinking of using a set since it will take the unique values and then enumerate with a counter of the index?

Upvotes: 0

Views: 41

Answers (2)

donbunkito
donbunkito

Reputation: 588

One could do it with defaultdict, like this:

from collections import defaultdict

indices_per_word = defaultdict(list)
for index, word in enumerate(listWords):
    indices_per_word[word].append(index)

indices_per_word

defaultdict(<type 'list'>, {'foobar': [2], 'foo': [0, 3], 'bar': [1, 4]})

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122252

Use a dictionary, and add indices to lists for the values:

indices_per_word = {}
for index, word in enumerate(listWords):
    indices_per_word.setdefault(word, []).append(index)

For your sample, this produces:

>>> listWords = ['foo', 'bar', 'foobar', 'foo', 'bar']
>>> indices_per_word = {}
>>> for index, word in enumerate(listWords):
...     indices_per_word.setdefault(word, []).append(index)
... 
>>> indices_per_word
{'bar': [1, 4], 'foo': [0, 3], 'foobar': [2]}
>>> for word, indices in indices_per_word.items():
...     print(word, indices)
... 
bar [1, 4]
foo [0, 3]
foobar [2]

Upvotes: 3

Related Questions