0

你能建议我一个字典理解来迭代项目列表并将它们在字典中散列,其值等于自动递增的整数 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
4

1 回答 1

2

您可以使用enumerate

>>> {k:v for v, k in enumerate(object_list, 1)}
{'goya': 5, 'noya': 4, 'thre': 2, 'tree': 3, 'trip': 1, 'voya': 6}
于 2013-11-17T13:25:14.263 回答