我使用字典和列表编写了以下代码:
d = computeRanks() # dictionary of id : interestRank pairs
lst = list(d) # tuples (id, interestRank)
interestingIds = []
for i in range(20): # choice randomly 20 highly ranked ids
choice = randomWeightedChoice(d.values()) # returns random index from list
interestingIds.append(lst[choice][0])
似乎有可能出错,因为我不确定lst和d.values()中的索引之间是否存在对应关系。你知道吗
你知道怎么写得更好吗?你知道吗
dict
的策略之一是,dict.keys()
和dict.values()
的结果将对应于,只要词典的内容不被修改。你知道吗正如@Ignacio所说,索引
choice
确实对应于lst
的预期元素,因此代码的逻辑是正确的。但是您的代码应该简单得多:d
已经包含元素的ID,所以重写randomWeightedChoice
以获取字典并返回ID也许它会帮助您知道可以使用
d.items()
迭代字典的键值对:相关问题 更多 >
编程相关推荐