Compare string with integer

I am just learning how to use python and lists. I have a list of examples as shown 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 try to run a loop that checks if the second item in each nested list exceeds 350,000, then prints the car, price and mileage, if so.

I used different loops forwith an expression ifinside it, but I can't figure it out.

+4
source share
3 answers

First, do not name the variable list, as it obscures the embedded file.

This is a very simple approach to 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']

, [i for i in l if int(i[1].replace(',','')) > 350000 ],

+6

, , , :

int(`i[1]`.replace(',',''))

, , ['Porsche', '400,000', '10,000km'], , , '400,000'. i[1].

, , 350 000. , . .

- (). .replace(',','') , "," ( - "," ).

- , "400 000" "400000". python, , 350000. , python . int() . , int('400000') 400000 40000.

400000 350000 .

+4

Python , :

cars = [['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 car, price, mileage in cars:
    if (int(price.replace(',', '')) > 350000):  # convert to int and compare
         print car, price, mileage

, (, ).

This means that you could also do this, which will work in other countries (provided that the numbers in the list have been formatted in accordance with its agreements):

import locale
locale.setlocale(locale.LC_ALL, '')  # set locale to platform default

for car, price, mileage in cars:
    if (locale.atoi(price) > 350000):  # convert to int and compare
         print car, price, mileage
+3
source

All Articles