python中三个不同取值范围的列表根据条件选择最佳索引

2024-04-26 17:18:35 发布

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

我有一个有三个键的dict,它由一个长度相同的列表组成。例如,键“a”有一个长度为5的列表,由0到6000的值组成。类似地,长度为5的键“b”的值范围为0到1.0。最后,具有相同长度的键“c”的值介于(1x1)到(2000x2000)之间。你知道吗

我必须选择一个介于0和4之间的索引,条件是“a”的值不能小于200。“b”的值不能低于0.95。然后,在满足这两个条件的指标中选择“c”的最高值。你知道吗

虚拟数据如下所示

  index     a          b           c
    0      600       0.99      (100x105)
    1      150        1.0       (50x40)
    2      820       0.75      (500x480)
    3      500       0.96      (200x190)
    4      400       0.97      (120x110)

这里,根据这两个条件,我可以将索引过滤为0、3和4。在这三个指数中,“c”的最大值是指数3。所以答案是3 500 0.96 (200x190)

如何以最有效的方式选择此选项?我想我可能需要用熊猫。我怎么能用熊猫来做呢?还有,如何以最具Python的方式来做呢?你知道吗

我对编码比较陌生。我很难弄明白。你知道吗

编辑: dict的代码片段

{
'a' : [600, 150, 820, 500, 400]
'b' : [0.99, 1.0, 0.75, 0.96, 0.97]
'c' : [(100,105), (50,40), (500,480), (200,190), (120,110)]
}

Tags: 数据答案代码编辑编码列表index选项
3条回答

这对于numpy来说是相对简单的,尽管c列的稍微奇怪的格式提供了一个有趣的转折点。你知道吗

import numpy as np

d = {
'a' : [600, 150, 820, 500, 400],
'b' : [0.99, 1.0, 0.75, 0.96, 0.97],
'c' : [(100,105), (50,40), (500,480), (200,190), (120,110)]
}

# Load as numpy arrays. 
d_np = {key: np.array(value) for key, value in d.items()}

# Create logical mask based on given requirements
mask = np.logical_and(d_np['a'] > 200, d_np['b'] > 0.95)

# Multiply 'c' along dimension 1
c_product = np.prod(d_np['c'], axis=1)

# Get index of maximum value. Note that this index is relative to masked array.
max_index_masked = np.argmax(c_product[mask])

# Get original 'c' value. Need to mask the array so that our indexing works.
max_value = d_np['c'][mask][max_index_masked]

# Get index relative to unmasked array
index = np.arange(d_np['c'].shape[0])[mask][max_index_masked]
print(index)

一个没有numpy的简单解决方案,使用列表切片

    data = {
        'a' : [600, 150, 820, 500, 400],
        'b' : [0.99, 1.0, 0.75, 0.96, 0.97],
        'c' : [(100,105), (50,40), (500,480), (200,190), (120,110)]
    }
    select_a = [index_a for index_a in range(len(data['a'])) if data['a'][index_a] >=200]
    select_b = [index_b for index_b in select_a if data['b'][index_b]>=0.95]
    result = select_b[0]
    for index_c in select_b:
        if((data['c'][index_c][0]*data['c'][index_c][1])>(data['c'][result][0]*data['c'][result][1])):
            result = index_c
    print(result)

以下是您的数据:

d = {'a':[600,150,820,500,400], 'b':[0.99,1.0,0.75,0.96,0.97], 'c':[(100,105),(50,40),(500,480),(200,190),(120,110)]}
a_thresh = 200
b_thresh = 0.95

这是解决问题的一种方法,只对字典中的列表进行一次检查:

from operator import mul

list_len = len(d['a'])
found_i = 0
for i in range(list_len):
    if ((d['a'][i]>=a_thresh) and (d['b'][i]>=b_thresh) and 
        (mul(*d['c'][i]) > mul(*d['c'][found_i]))):
        found_i = i
print (found_i)

输出:

3

当然,您可以不用导入和使用mul()函数来实现这一点。它只是使循环条件显得有点紧凑。mul()只是将元组的两部分相乘。要在没有mul()的情况下执行此操作,请搜索(mul(*d['c'][3]) > mul(*d['c'][found_i])),并用较长的表达式((d['c'][3][0]*d['c'][3][1]) > (d['c'][found_i][0]*d['c'][found_i][1]))替换(mul(*d['c'][3]) > mul(*d['c'][found_i]))

相关问题 更多 >