2

私は次のものを持っています:

strlist = ['the', 'the', 'boy', 'happy', 'boy', 'happy']
{x:{(list(enumerate(strlist))[y])[0]} for y in range(len(strlist)) for x in (strlist)}

私の出力は次のとおりです。

{'boy': set([5]), 'the': set([5]), 'happy': set([5])}

私の問題は、これを出力したいということです(python 3.xを使用):

{'boy': {2,4}, 'the': {0,1}, 'happy': {3,5} }

どんな助けでも素晴らしいでしょう!

ありがとう

4

2 に答える 2

2
>>> strlist = ['the', 'the', 'boy', 'happy', 'boy', 'happy']
>>> from collections import defaultdict
>>> D = defaultdict(set)
>>> for i, s in enumerate(strlist):
...     D[s].add(i)
... 
>>> D
defaultdict(<type 'set'>, {'boy': {2, 4}, 'the': {0, 1}, 'happy': {3, 5}})

defaultdict何らかの理由で使用できない場合

>>> D = {}
>>> for i, s in enumerate(strlist):
...     D.setdefault(s, set()).add(i)
... 
>>> D
{'boy': {2, 4}, 'the': {0, 1}, 'happy': {3, 5{}

これは、理解としてそ​​れを書く愚かな(非効率的な)方法です

>>> {k: {i for i, j in enumerate(strlist) if j == k} for k in set(strlist)}
{'boy': {2, 4}, 'the': {0, 1}, 'happy': {3, 5}}
于 2013-07-03T23:51:01.770 に答える