Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Picking the threshold value for list elements in Python

I have a list Cb. If any element of Cb is greater than threshold_Cb, I want to be that element equal to threshold_Cb. But I am getting error. I present the expected output.

Cb=[[0.001,
  7.557543577091797e-06,
  1656.90]]

threshold_Cb=10.0

if Cb > threshold_Cb:
    Cb = threshold_Cb
    print(Cb)

The error is

in <module>
    if Cb > threshold_Cb:

TypeError: '>' not supported between instances of 'list' and 'float'

The expected output is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Cb=[[0.001,
  7.557543577091797e-06,
  10.0]]

>Solution :

You need to iterate over every item in the nested list and compare them individually:

Cb=[[0.001,
  7.557543577091797e-06,
  1656.90]]

threshold_Cb=10.0
# Iterating over the first list within the nested list you have
for index, value  in enumerate(Cb[0]):
    # checking if the value is above treshold
    if value > threshold_Cb:
        # Reassigning the value with index
        Cb[0][index] = threshold_Cb
print(Cb)

Output:

[[0.001, 7.557543577091797e-06, 10.0]]

Otherwise your "if" statement is comparing if a nested list is larger than an integer and that is not a meaningful comparison. Hence your error message.

When Cb has more than one lists inside it you can do this:

# iterating over nested lists inside Cb
for lst_index, lst in enumerate(Cb):
    # Iterating over the nested list values
    for value_index, value  in enumerate(lst):
        # checking if the value is above treshold
        if value > threshold_Cb:
            # Reassigning the value with index
            Cb[lst_index][value_index] = threshold_Cb
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading