Home > Software design >  Finding the minimum of a nested list that has a constant in element[1]
Finding the minimum of a nested list that has a constant in element[1]

Time:01-10

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].

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

    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.

Any ideas on how to do this?

CodePudding user response:

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)

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))])

CodePudding user response:

You can define function like this:

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)

CodePudding user response:

I am a beginner in Python so my solution can be too complicated.

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.

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.

For example

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