通过使用键作为列表索引,将python字典转换/映射到列表

2024-04-24 10:09:55 发布

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

我有一本python字典,如下所示:

dict = {4:0.65,8:1.23,3:0.43}

我想通过使用键作为列表的索引将其转换为python列表。期望的转换结果是:

listLength = 10
plist = [0,0,0,0.43,0.65,0,0,0,1.23,0]

我知道如何使用循环来完成上面的操作,但这不是pythonic,也不是很快。在不使用循环的情况下,实现上述操作的最python方法是什么。你知道吗

我特别需要用最好的表现来完成上面的工作。你知道吗


Tags: 方法列表字典情况pythonicdictplistlistlength
3条回答

对于较大的数据集,可以直接在键和值迭代器上使用np.fromiter,而不是先创建列表,从而获得一定的速度。你知道吗

创建测试用例

>>> d = dict(zip(np.random.randint(1, 10, 1_000_000).cumsum(), np.arange(1_000_000.)))
>>> out = np.zeros(10_000_000)

定义fromiter方法

>>> def use_iter():
...     k, v = (np.fromiter(w, dtype=t, count=len(d)) for w, t in [(d.keys(), int), (d.values(), float)])
...     out[k] = v
...     return out

list方法供参考

>>> def use_list():
...     out[list(d.keys())] = list(d.values())
...     return out

给他们计时

>>> timeit(use_iter, number=100)
4.2583943260106025
>>> timeit(use_list, number=100)
17.10310926999955

同时,检查正确性

>>> np.all(use_list() == use_iter())
True

既然您标记了pandas,那么来自reindex的解决方案

pd.Series(d).reindex(range(10),fill_value=0).tolist()
Out[369]: [0.0, 0.0, 0.0, 0.43, 0.65, 0.0, 0.0, 0.0, 1.23, 0.0]

使用numpynumpy索引将是最有效的解决方案:

out = np.zeros(10)
out[list(d.keys())] = list(d.values())

array([0.  , 0.  , 0.  , 0.43, 0.65, 0.  , 0.  , 0.  , 1.23, 0.  ])

性能因为您要求:

k = np.random.randint(1, 100000, 10000)
v = np.random.rand(10000)
d = dict(zip(k, v))

In [119]: %%timeit
     ...: out = np.zeros(100000)
     ...: out[list(d.keys())] = list(d.values())
     ...:
     ...:
1.86 ms ± 13.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [120]: %timeit [d.get(i, 0) for i in range(100000)]
17.4 ms ± 231 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [121]: %timeit pd.Series(d).reindex(range(100000),fill_value=0).tolist()
9.77 ms ± 148 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

相关问题 更多 >