将长列表/数组放入以索引为键的字典中

2024-04-19 23:21:08 发布

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

我正在尝试解决一个编码练习。 它的一部分是从整数的随机列表创建字典。 字典必须具有原始列表中元素的索引askey,以及列表中元素asvalue。你知道吗

这是我的职责:

def my_funct(pricesLst):
    price_dict = {}
    for i in range(0, len(pricesLst)):
        price_dict[i] = pricesLst[i]

    print(price_dict)


a = np.random.randint(1,100,5)

my_funct(a)

我得到的输出是右边的:

{0: 42, 1: 23, 2: 38, 3: 27, 4: 61}

但是如果列表较长,我会得到一个奇怪的结果作为输出。你知道吗

示例:

a = np.random.randint(1,1000000000,5000000)
my_funct(a)

输出为:

{2960342: 133712726, 2960343: 58347003, 2960344: 340350742, 949475: 944928187.........4999982: 417669027, 4999983: 650062265, 4999984: 656764316, 4999985: 32618345, 4999986: 213384749, 4999987: 383964739, 4999988: 229138815, 4999989: 203341047, 4999990: 54928779, 4999991: 139476448, 4999992: 244547714, 4999993: 790982769, 4999994: 298507070, 4999995: 715927973, 4999996: 365280953, 4999997: 543382916, 4999998: 532161768, 4999999: 598932697}

我不知道为什么会这样。 为什么我的字典的键不是从0开始的,就像最短列表那样?你知道吗

我唯一能想到的是列表太长,因此python没有使用从0开始的索引作为键,而是将内存中的空间关联起来。你知道吗


Tags: 元素编码列表字典mynp整数random
2条回答

这些词典是在python3.7中排序的。如果您是较旧的python版本(<;3.7),则必须使用有序字典。你知道吗

您可以按如下方式使用有序词典:

from collections import OrderedDict
import numpy as np
def my_funct(pricesLst):
    price_dict = OrderedDict()
    for i in range(0, len(pricesLst)):
        price_dict[i] = pricesLst[i]
    print(price_dict)

a = np.random.randint(1,10000,10000)

my_funct(a)

因为python中的dict不一定是有序的。您应该使用一个有序字典,它声明为:

my_ordered_dict=OrderedDict()

相关问题 更多 >