源于字典的列表索引之间的对应关系

2024-10-02 00:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()中的索引之间是否存在对应关系。你知道吗

你知道怎么写得更好吗?你知道吗


Tags: of代码id列表dictionary字典listvalues
2条回答

dict的策略之一是,dict.keys()dict.values()的结果将对应于,只要词典的内容不被修改。你知道吗

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

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

for k, v in d.items():
    etc.

相关问题 更多 >

    热门问题