Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 源于字典的列表索引之间的对应关系_Python_List_Dictionary_Indices - Fatal编程技术网

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

Python 源于字典的列表索引之间的对应关系,python,list,dictionary,indices,Python,List,Dictionary,Indices,我使用字典和列表编写了以下代码: 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

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

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所说,索引
选项
确实对应于
lst
的预期元素,因此代码的逻辑是正确的。但是您的代码应该简单得多:
d
已经包含元素的ID,所以重写
randomWeightedChoice
以获取字典并返回ID

也许它会帮助您知道,您可以使用
d.items()


为什么需要
lst
?您可以从
d
(使用
d.keys()
)中随机选择一个键,并将其添加到
interestingIds
@simeonviser我不能这样做,因为它是随机的,权重和权重都是在d.values()中的interestrank。
d
的类型是什么?@alexis list of(int,float) tuples@alexis对不起,我写了上面的lst类型。
d
的类型是int字典:float pairs,我没有这么说。但是这部分不会有太大的变化。您显示了
dict.keys()
dict.values()
对应,但问题是
lst(dict)
而不是
dict.keys()
。这会有区别吗?不会。通过
列表(dict)
迭代
dict
将遵从
dict.iterkeys()
,这会产生影响。哦,对于重写,您应该修改randomWeightedChoice()。想想sorted()和max()的作用。重写不是问题,但我不想重写,因为我主要对列表使用此函数,不想为每个特殊的数据结构创建新函数。randomWeightedChoice获取一个列表并从此列表返回索引。它不会被重写。我需要生成正好20个随机数,所以不需要迭代所有的键值对。你不需要迭代,这是一个演示
randomWeightedChoice
需要检查所有值才能完成其工作,因此它在某个地方有一个循环。如果你不能重写它,我不认为我们还有什么可以帮助的。是的,randomWeightedChoice需要检查所有的值20次来选择20个随机值。不,它没有。它只需要检查一次。但如果你不重写它又有什么关系呢?如果我重写这个问题就没有意义了。我希望具有唯一的接口,而不是对各种数据结构(dict、list、set等)具有相同的功能。
for k, v in d.items():
    etc.