【问题标题】:Generating an inverse index生成反向索引
【发布时间】:2013-07-03 23:47:11
【问题描述】:

我有以下几点:

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} }

任何帮助都会很棒!

谢谢

【问题讨论】:

  • @KarolyHorvath:这有什么令人惊讶的?这是strlist'boy'这两个索引的集合。
  • @abarnert: >>> {2,4} SyntaxError: invalid syntax
  • @KarolyHorvath:>>> {2,4}set([2, 4])。 Python 3.x 已经设置了文字。 2.7也是如此。如果您要回答 Python 3.x 的问题,请不要尝试在 2.5 中运行代码。
  • @abarnert:对不起,我根本不知道集合文字。

标签: python dictionary python-3.x inverse


【解决方案1】:
>>> 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}}

【讨论】:

  • @ gribbler 不幸的是,它需要是一个理解并且没有 defaultdict 使用:/
  • @JessePet,理解的要求是愚蠢的(你可以告诉你的老师我说过)。它无缘无故地迫使您使用效率低下的算法。
【解决方案2】:

试试

dict(((string, set(i for i,w in enumerate(strlist) if w == string)) for string in strlist))

但请注意,它具有二次运行时间,因此它仅适用于非常少量的数据。

测试用例和样本输出http://ideone.com/4sxUNf

【讨论】:

  • 这很接近,但我想保留它的形式:{string:{i:j} for string in ...} etc.
  • 我试图操纵你所拥有的,并想出了这个: {string:{i} for (i,j) in enumerate(strlist) for string in strlist if j==string} 但是,我仍然得到: {'boy': set([4]), 'the': set([1]), 'happy': set([5])}
  • @JessePet,您使用的是哪个版本的 Python?看起来更像 Python2 输出
  • @gnibbler:我使用的是 python 3.2.3。
  • @JessePet,Python 3.2.3 不会像 set([4]) 这样打印集合,它会打印 {4}。再次检查您运行的版本是否正确
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
  • 2017-12-23
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
  • 2021-12-01
  • 2012-08-18
相关资源
最近更新 更多