I have 3 lists and 1 value:
my_value = 500
minimal_values = ['0,32', '0,35', '0,45']
maximal_values = ['0,78', '0,85', '0,72']
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']]
Right now I'am filtering my code and trying to do a subtstraction of my_value
- index [2]
in results
. Filtering is going well, its just the substraction that doesnt work in my output yet. Below is the code:
# Convert values to float.
minimal_values = [float(i.replace(',', '.')) for i in minimal_values]
maximal_values = [float(i.replace(',', '.')) for i in maximal_values]
# Collect all unique countries in a list.
countries = list(set(country[0] for country in my_list))
results = []
for l in my_list:
i = countries.index(l[0])
if minimal_values[i] <= float(l[-1].replace(',', '.')) <= maximal_values[i]:
new_index_2 = my_value - float(l[-2].replace(',', '.')) #<--- this is where I do the substraction
results.append(l)
print(results)
This is the output I get:
[['Morocco', 'Meat', '189,90', '0,32'],
['Morocco', 'Meat', '189,38', '0,44'],
['Morocco', 'Meat', '188,94', '0,60'],
['Morocco', 'Meat', '188,49', '0,78'],
['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', '189,32', '0,45'],
['Italy', 'Meat', '188,61', '0,67'],
['Italy', 'Meat', '188,01', '0,72']]
As you can see, its not substracting 500
- index [2]
....
This is the output I want:
[['Morocco', 'Meat', '310,10', '0,32'],
['Morocco', 'Meat', '310,62', '0,44'],
['Morocco', 'Meat', '311,06', '0,60'],
['Morocco', 'Meat', '311,51', '0,78'],
['Spain', 'Meat', '310,44', '0,35'],
['Spain', 'Meat', '310,99', '0,40'],
['Spain', 'Meat', '311,87', '0,75'],
['Spain', 'Meat', '312,05', '0,85'],
['Italy', 'Meat', '310,68', '0,45'],
['Italy', 'Meat', '311,39', '0,67'],
['Italy', 'Meat', '311,99', '0,72']]
The only thing you are missing is updating the list after subtraction.
Just add this line to your code after getting new_index_2.
new_index_2 = my_value - float(l[-2].replace(',', '.'))
l[-2] = new_index_2 #update the value back to list
results.append(l)
you can still improve the readability by giving the meaning full names to variables.