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