-1

我使用字典和列表编写了以下代码:

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])

似乎可能存在错误,因为我不确定lstd.values()中的索引之间是否存在对应关系。

你知道如何更好地写这个吗?

4

2 回答 2

3

的策略之一dict只要字典的内容不被修改dict.keys(),和的结果dict.values()就会对应。

于 2012-03-18T12:41:51.277 回答
0

正如@Ignacio 所说,索引choice确实对应于 的预期元素lst,因此您的代码逻辑是正确的。但是您的代码应该更简单:d已经包含元素的 ID,因此重写randomWeightedChoice以获取字典并返回一个 ID。

也许它会帮助您知道您可以使用以下方法迭代字典的键值对d.items()

for k, v in d.items():
    etc.
于 2012-03-18T13:03:45.740 回答