0

I am new in python and im trying to convert the list L =["11.4K" , "550" , "1.23M" , "30"]to : L=["11400" , "550" , "1230000" , "30"] I believe that K means 1000 and M means 1000000

Note: what if only one number in the list is in the form of K or M and what happens if the position of displayed numbers ( K, M ) will not remain in the same place of the list. eg: what happens in this case: L1=[23 , 9.7K , 34 , 900] convert to : L1=[23 , 9700 , 34 , 900]

  • 1
    what did you code already? – MaxU - stand with Ukraine Feb 24 '16 at 21:05
  • 3
    Are these values strings? None of `11.4K`, `1.23M`, or `1.230.000` are valid Python literals (and `11.400` doesn't mean eleven-thousand, four hundred, it means eleven and four-tenths). Please clarify your question. – ChrisGPT was on strike Feb 24 '16 at 21:05
  • @Chris that depend in what part of the world you are, in some places 11.400 = 11400 while in others 11400 = 11,400 – Copperfield Feb 24 '16 at 21:33
  • @Copperfield, my comment was about Python literals, which work the same irrespective of location. (If you view earlier versions of the question where none of the values were quoted it might make more sense. See also the different way I commented on `1.230.000` and `11.400`.) Thousands separators don't exist in literals at all, and are only relevant when we present numbers to the user. In that situation you are correct. – ChrisGPT was on strike Feb 24 '16 at 21:39
  • 1
    There seem to be a few libraries to do this, in both directions. See e.g. this related question: http://stackoverflow.com/q/3154460/1639625 – tobias_k Feb 24 '16 at 21:40

1 Answers1

1

a quick fix could be

>>> num=["11.4K" , "550" , "1.23M" , "30"]
>>> units {"K":1000,"M":1000000}  # make a dict that contain the value that they represent
>>> result=[]
>>> for n in num:
        try:
            result.append( float(n) )  #try to comber it to a number
        except ValueError:
            unit=n[-1]                 #get the letter
            n = float( n[:-1] )        #convert all but the letter
            result.append( n * units[unit] )

>>> result
[11400.0, 550.0, 1230000.0, 30.0]
>>> 
Copperfield
  • 8,131
  • 3
  • 23
  • 29