我有一个类型为-的字典
{
'a': [0, 0, 0, 1, 1, 1],
'diff': [-3.654748632042965, -3.97342251742816, -4.010696955187965, -6.3903113605617685, -6.310284875983931, -4.0363808384515005],
'b': [-1, 0, 1, -1, 0, 1]
}
我想选择与最小'diff'相对应的a
和b
值,在这种情况下,它们应为与-6.3903相对应的[1,-1]。我是python新手,无法弄清楚!
答案 0 :(得分:0)
您可以使用numpy.argmin()
import numpy as np
d = {'a': [0, 0, 0, 1, 1, 1], 'diff': [-3.654748632042965, -3.97342251742816, -4.010696955187965, -6.3903113605617685, -6.310284875983931, -4.0363808384515005], 'b': [-1, 0, 1, -1, 0, 1]}
ind = np.argmin(d["diff"])
a = d["a"][ind]
b = d["b"][ind]
print([a, b])
OUT:
[1, -1]
答案 1 :(得分:0)
使用min
查找列表的最小值,然后使用index
查找最小值的索引,然后从a
和{{1}中获取相应索引的元素}
b
输出
d={'a': [0, 0, 0, 1, 1, 1], 'diff': [-3.654748632042965, -3.97342251742816, -4.010696955187965, -6.3903113605617685, -6.310284875983931, -4.0363808384515005], 'b': [-1, 0, 1, -1, 0, 1]}
a=d['a']
b=d['b']
diff=d['diff']
index=diff.index(min(diff))
print([a[index],b[index]])
答案 2 :(得分:0)
这很简单,如果您知道如何处理字典。这是我在python中的示例代码:
def diff(dict):
min = 0
position = 0
for index in range(len(dict["diff"])):
checkValue = dict["diff"][index]
if (checkValue < min):
min = checkValue
position = index
print([dict["a"][position],dict["b"][position]])
diff({'a': [0, 0, 0, 1, 1, 1], 'diff': [-3.654748632042965, -3.97342251742816, -4.010696955187965, -6.3903113605617685, -6.310284875983931, -4.0363808384515005], 'b': [-1, 0, 1, -1, 0, 1]})
输出:
[1,-1]
答案 3 :(得分:0)
您可以将min
用于zip
的拆包:
from operator import itemgetter
a, diff_min, b = min(zip(*itemgetter('a', 'diff', 'b')(d)), key=itemgetter(1))
print(a, diff_min, b)
1 -6.3903113605617685 -1