Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare a string to an integer

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.

like image 662
Ravash Jalil Avatar asked Dec 12 '22 00:12

Ravash Jalil


1 Answers

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

like image 103
Bhargav Rao Avatar answered Jan 08 '23 22:01

Bhargav Rao