I'm just learning how to use python and lists. I have a sample list like the one below.
list = [['Ferrari','200,000','10,000km'],['Porsche','230,000','10,000km'],['Ferrari','150,000','10,000km'],['Ferrari','200,000','10,000km'],['Porsche','230,000','10,000km'],['Porsche','200,210','10,000km'],['Ferrari','110,000','10,000km'],['Porsche','400,000','10,000km'],
I'm trying to run a loop that checks if the 2nd element in each nested list is greater than 350,000, then prints the car, price, and mileage if it is.
I've used different for
loops with an if
statement inside of it, but can't figure it out.
Firstly do not name your variable list
as it shadows the builtin.
This is a very simple approach of solving your problem
>>> l = [['Ferrari','200,000','10,000km'],['Porsche','230,000','10,000km'],['Ferrari','150,000','10,000km'],['Ferrari','200,000','10,000km'],['Porsche','230,000','10,000km'],['Porsche','200,210','10,000km'],['Ferrari','110,000','10,000km'],['Porsche','400,000','10,000km']]
>>> for i in l:
... if (int(i[1].replace(',','')) > 350000): # Remove all the , in your string and type cast it to an integer
... print i
...
['Porsche', '400,000', '10,000km']
You can do it in a list comprehension as in [i for i in l if int(i[1].replace(',','')) > 350000 ]
which will do everything for you in a single line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With