我有以下几点:
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} }任何帮助都是最好的!
谢谢
发布于 2013-07-04 07:51:02
>>> 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-04 07:54:08
试一试
dict(((string, set(i for i,w in enumerate(strlist) if w == string)) for string in strlist))但请注意,它有二次运行时,因此它只对非常少量的数据有用。
测试用例和示例输出:http://ideone.com/4sxUNf
https://stackoverflow.com/questions/17459882
复制相似问题