I have a dictionary
我有一本字典
mydict = {'jon': 12, 'alex': 17, 'jane': 13}
mydict = {'jon':12,'alex':17,'jane':13}
and I want to create a np.array
which contains the values 12, 17, 13
, but sorted by another array
我想创建一个包含值12,17,13的np.array,但是按另一个数组排序
sortby = np.array(['jon', 'jane', 'alex'])
sortby = np.array(['jon','jane','alex'])
which should yield the output as
应该产生的输出为
sorted_array = np.array([12, 13, 17])
sorted_array = np.array([12,13,17])
Any approaches that are more efficient than looping through the sortby
array like below?
任何比循环排序数组更有效的方法如下所示?
sorted_array = []
for vals in sortby:
sorted_array.append(mydict[vals])
return np.array(sorted_array)
1 个解决方案
#1
2
Use list comprehension,
使用列表理解,
In [100]: np.array([mydict[i] for i in sortby])
Out[100]: array([12, 13, 17])
Edit:
Execution timings, To make clear for mohammad and Moses Discussions
执行时间,明确*和摩西的讨论
In [119]: def test_loop():
sorted_array = []
for vals in sortby:
sorted_array.append(mydict[vals])
return np.array(sorted_array)
.....:
In [120]: def test_list_compres():
return np.array([mydict[i] for i in sortby])
.....:
In [121]: %timeit test_list_compres
10000000 loops, best of 3: 20 ns per loop
In [122]: %timeit test_loop
10000000 loops, best of 3: 21.3 ns per loop
In [123]: %timeit test_list_compres
10000000 loops, best of 3: 20.1 ns per loop
In [124]: %timeit test_loop
10000000 loops, best of 3: 21.9 ns per loop
It's a marginal difference but it will make a significant change with huge entries.
这是一个边际差异,但它将通过巨大的条目做出重大改变。
#1
2
Use list comprehension,
使用列表理解,
In [100]: np.array([mydict[i] for i in sortby])
Out[100]: array([12, 13, 17])
Edit:
Execution timings, To make clear for mohammad and Moses Discussions
执行时间,明确*和摩西的讨论
In [119]: def test_loop():
sorted_array = []
for vals in sortby:
sorted_array.append(mydict[vals])
return np.array(sorted_array)
.....:
In [120]: def test_list_compres():
return np.array([mydict[i] for i in sortby])
.....:
In [121]: %timeit test_list_compres
10000000 loops, best of 3: 20 ns per loop
In [122]: %timeit test_loop
10000000 loops, best of 3: 21.3 ns per loop
In [123]: %timeit test_list_compres
10000000 loops, best of 3: 20.1 ns per loop
In [124]: %timeit test_loop
10000000 loops, best of 3: 21.9 ns per loop
It's a marginal difference but it will make a significant change with huge entries.
这是一个边际差异,但它将通过巨大的条目做出重大改变。