I have the following 2 lists.
my_values = ['0,78', '0,40', '0,67']
my_list = [
['Morocco', 'Meat', '190,00', '0,15'],
['Morocco', 'Meat', '189,90', '0,32'],
['Morocco', 'Meat', '189,38', '0,44'],
['Morocco', 'Meat', '188,94', '0,60'],
['Morocco', 'Meat', '188,49', '0,78'],
['Morocco', 'Meat', '187,99', '0,101'],
['Spain', 'Meat', '190,76', '0,10'],
['Spain', 'Meat', '190,16', '0,20'],
['Spain', 'Meat', '189,56', '0,35'],
['Spain', 'Meat', '189,01', '0,40'],
['Spain', 'Meat', '188,13', '0,75'],
['Spain', 'Meat', '187,95', '0,85'],
['Italy', 'Meat', '190,20', '0,11'],
['Italy', 'Meat', '190,10', '0,31'],
['Italy', 'Meat', '189,32', '0,45'],
['Italy', 'Meat', '188,61', '0,67'],
['Italy', 'Meat', '188,01', '0,72'],
['Italy', 'Meat', '187,36', '0,80']]
Now for every lists in my_list
I want to check at what index[2]
is index[3]
equal to a value in my_values.
index[2]
is the 3th row in my_list
and index[4]
is the 4th row in my_list
So short said:
index[2]
is index[3]
== 0,78
index[2]
is index[3]
== 0,40
index[2]
is index[3]
== 0,67
This is the code I tried:
my_answers = []
for key,sublists in itertools.groupby(my_list,lambda y:y[0]):
v = min(x for x in sublists if float(x[3].replace(',', '.')) == x for x in my_values);
my_answers.append(v[-2])
print(my_answers)
This is what I receive:
ValueError: min() arg is an empty sequence
This is what I expected:
188,49
189,01
188,61
Is this what you want?
my_values = ['0,78', '0,40', '0,67']
my_list = [
['Morocco', 'Meat', '190,00', '0,15'],
['Morocco', 'Meat', '189,90', '0,32'],
['Morocco', 'Meat', '189,38', '0,44'],
['Morocco', 'Meat', '188,94', '0,60'],
['Morocco', 'Meat', '188,49', '0,78'],
['Morocco', 'Meat', '187,99', '0,101'],
['Spain', 'Meat', '190,76', '0,10'],
['Spain', 'Meat', '190,16', '0,20'],
['Spain', 'Meat', '189,56', '0,35'],
['Spain', 'Meat', '189,01', '0,40'],
['Spain', 'Meat', '188,13', '0,75'],
['Spain', 'Meat', '187,95', '0,85'],
['Italy', 'Meat', '190,20', '0,11'],
['Italy', 'Meat', '190,10', '0,31'],
['Italy', 'Meat', '189,32', '0,45'],
['Italy', 'Meat', '188,61', '0,67'],
['Italy', 'Meat', '188,01', '0,72'],
['Italy', 'Meat', '187,36', '0,80'],
]
print("\n".join(i[2] for i in my_list if i[3] in my_values))
Output:
188,49
189,01
188,61
Here's what the one-liner does:
my_list
and checks the value from each sub-list with the index [3]
againts the my_value
listTrue
, it "keeps" the value from index [2]
values
that matched the above e.g. 189,01
i[2] for i in my_list if i[3] in my_values
is a generator"\n"
is a new line characterEDIT:
If you want the output to be in a list, just do this:
yet_another_list = [i[2] for i in my_list if i[3] in my_values]
print(yet_another_list)
This gives you:
['188,49', '189,01', '188,61']