【问题标题】:How to implement inverted index from string list to dictionary using dict comprehension and auto-incremental id?如何使用字典理解和自动增量ID实现从字符串列表到字典的倒排索引?
【发布时间】:2013-11-17 13:21:38
【问题描述】:

你能建议我一个字典理解来迭代项目列表并在字典中散列它们,值等于自动递增的整数 id 吗?或者某种从生成器或其他列表中获取价值的方法?

有没有可能是这样的:

iverted_index_dict = {key: (auto_increment_here) in object_list }

我目前的解决方案:

object_list = ["trip", "thre", "tree", "noya", "goya", "voya"]


invid1 = {object_list[i]: i+1 for i in xrange(0,len(object_list))}
print invid1

invid2 = {}
i=0
for item in object_list:
    i += 1
    invid2[item] = i

print invid2

【问题讨论】:

    标签: python list dictionary compression inverted-index


    【解决方案1】:

    你可以使用enumerate:

    >>> {k:v for v, k in enumerate(object_list, 1)}
    {'goya': 5, 'noya': 4, 'thre': 2, 'tree': 3, 'trip': 1, 'voya': 6}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多