you can use the itertools module for this
>>> import itertools
>>> my_list = [
['Morocco', 'Fish', '0,012'],
['Morocco', 'Fish', '0,153'],
['Morocco', 'Fish', '0,114'],
['Morocco', 'Fish', '0,109'],
['Morocco', 'Fish', '0,252'],
['Spain', 'Fish', '0,012'],
['Spain', 'Fish', '0,113'],
['Spain', 'Fish', '0,116'],
['Spain', 'Fish', '0,250'],
['Spain', 'Fish', '0,266'],
['Italy', 'Fish', '0,112'],
['Italy', 'Fish', '0,025'],
['Italy', 'Fish', '0,224'],
['Italy', 'Fish', '0,256'],
['Italy', 'Fish', '0,245']]
>>> my_limit = 0.2
>>> for key,sublists in itertools.groupby(my_list,lambda y:y[0]):
v=[] #we initialize it in case no element fulfill the condition
for v in itertools.takewhile(lambda x:float(x[-1].replace(",","."))<my_limit ,sublists):
pass
if v:
print(v,"->",v[-1])
['Morocco', 'Fish', '0,109'] -> 0,109
['Spain', 'Fish', '0,116'] -> 0,116
['Italy', 'Fish', '0,025'] -> 0,025
>>>
here with groupby we, well, group together all the consecutive sublist that have the same value in a given position we specify, which in this case is the first position, then we go into those sublist and take those that fulfill our condition and stop at the first that doesn't with takewhile and from those we only want the last one which will stored into v
at the end of the loop.
I make that grouping because that make more sense to my, but if grouping like that isn't necessary, we can also use groupby to split the list into the subsection that fulfill the condition and those that do not by changing the grouping key
>>> my_list = [
['Morocco', 'Fish', '0,012'],
['Morocco', 'Fish', '0,153'],
['Morocco', 'Fish', '0,114'],
['Morocco', 'Fish', '0,109'],
['Morocco', 'Fish', '0,252'],
['Morocco', 'Fish', '0,002'],#extra
['Morocco', 'Fish', '0,252'],#extra
['Spain', 'Fish', '0,012'],
['Spain', 'Fish', '0,113'],
['Spain', 'Fish', '0,116'],
['Spain', 'Fish', '0,250'],
['Spain', 'Fish', '0,266'],
['Spain', 'Fish', '0,066'], #extra
['Spain', 'Fish', '0,366'], #extra
['Italy', 'Fish', '0,112'],
['Italy', 'Fish', '0,025'],
['Italy', 'Fish', '0,224'],
['Italy', 'Fish', '0,256'],
['Italy', 'Fish', '0,245'],
['Italy', 'Fish', '0,005'],#extra
['Italy', 'Fish', '0,305']]#extra
>>> for condition,sublist in itertools.groupby(my_list,lambda x:float(x[-1].replace(",","."))<my_limit):
if condition:
for v in sublist:
pass
print(v,"->",v[-1])
['Morocco', 'Fish', '0,109'] -> 0,109
['Morocco', 'Fish', '0,002'] -> 0,002
['Spain', 'Fish', '0,116'] -> 0,116
['Spain', 'Fish', '0,066'] -> 0,066
['Italy', 'Fish', '0,025'] -> 0,025
['Italy', 'Fish', '0,005'] -> 0,005
>>>