简体   繁体   中英

Having trouble converting a list of strings into numbers

So I got a list here:

list1 = ["yo dog", "2", "it's ya boi", "jake", "69.420"]

And I want its output to be this so that all the numbers in my list are now "floats" but still string form:

["yo dog", "2.0", "it's ya boi", "jake", "69.420"]

This is what I tried:

list1 = [float(x) for x in list1 if is_number(x)]

list1 = [str(x) for x in list1]

Basically it leaves me with:

["2.0", "69.420"] and removes everything else that's not a number. This is obvious because I'm making my old list equal to only the strings that have numbers in them.

(is_number() btw is my function to check if a string contains a number)

So obviously I could make a for loop and add stuff together again, but I was wondering if there was a better way to do this.

I HAVE NEGATIVE NUMBERS!!!

you could use a regular expression:

import re 

list1 = ["yo dog", "2", "it's ya boi", "jake", "69.420"]

[str(float(e)) if re.match(r'^-?\d+(?:\.\d+)?$', e) else e  for e in list1 ]

output:

['yo dog', '2.0', "it's ya boi", 'jake', '69.42']
list1 = ["yo dog", "2", "it's ya boi", "jake", "69.420"]

float_list = []

for string in list1:
    try:
        float_list.append(str(float(string)))
    except ValueError:
        #float_list.append(string) # if you want to keep string
        pass # if you don't want the string

print(float_list)

You could use the try/except statement to attempt a conversion and just return the original strings when it fails:

def floater(s):
    try:    return str(float(s))
    except: return s

list1 = ["yo dog", "-2", "it's ya boi", "jake", "69.420"]

result = list(map(floater,list1))

print(result)
['yo dog', '-2.0', "it's ya boi", 'jake', '69.42']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM