简体   繁体   English

查找在 element[1] 中具有常数的嵌套列表的最小值

[英]Finding the minimum of a nested list that has a constant in element[1]

I have a nested list:我有一个嵌套列表:

list = [[4, 2], [3, 2], [1, 1]]

And I want to find the minimum number in index[0] that has a constant (value) of 2 in index[1].我想在 index[1] 中找到常数(值)为 2 的 index[0] 中的最小数字。

For this list elements 1 and 2 have a value of 2 at index[1] within the nested list therefore the 4 and 3 fit the criteria and the min number is 3 so the output should be 3对于此列表,元素 1 和 2 在嵌套列表中的索引 [1] 处的值为 2,因此 4 和 3 符合标准,最小数为 3,因此 output 应为3

    for val in freqList:
        print(val[0])

Gives me the values in index[0] of the list but I'm not sure how to only print the values of index[0] that have a value of 2 in index[1] and then how to select the minimum.给我列表的 index[0] 中的值,但我不确定如何仅打印 index[1] 中值为 2 的 index[0] 的值,然后如何将 select 打印到最小值。

Any ideas on how to do this?关于如何做到这一点的任何想法?

If you want to get minimum of the first elements in the inner lists:如果要获取内部列表中第一个元素的最小值:

min([val[0] for val in freqList])

Also if you want to check inner lists for conditions:此外,如果您想检查内部列表的条件:

min([val[0] for val in freqList if CONDITION)

which if your condition is val[1] == 2 (Also your question's answer)如果您的条件是val[1] == 2 (也是您的问题的答案)

min([val[0] for val in freqList if val[1] == 2])

or even you can check for multiple condition:甚至您可以检查多个条件:

min([val[0] for val in freqList if ((val[1] == 2) and (len(val) == 2))])

I am a beginner in Python so my solution can be too complicated.我是 Python 的初学者,所以我的解决方案可能太复杂了。

I can suggest the following approach我可以建议以下方法

lst2 = []
for sublist in lst:
    if len( sublist ) >= 2 and sublist[1] == 2:
        lst2.append( sublist[0] )
min_value = min( lst2 )

where lst is you original list of lists.其中lst是您的原始列表列表。

Using the built list lst2 you can output all values at index 0 of sub-lists that have at index 1 a value equal to 2.使用构建的列表lst2您可以 output 索引 1 处的值等于 2 的子列表的索引 0 处的所有值。

For example例如

for value in lst2:
    print( value, end = ' ' )
print()
print( min( lst2 ) )

You can define function like this:您可以像这样定义 function :

def find_minimum(where, const_id, const_val):
    values = []

    for i in where:
        if i[const_id] == const_val:
            values.append(i[0])

    return min(values)

Usage:用法:

list = [[4, 2], [3, 2], [1, 1]]
minimum = find_minimum(list, 1, 2)
print(minimum)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM