1

I'm trying to learn Python and i have a problem, so if i have something like that:

data_l = ['data', '18.8', '17.9', '0.0']

How do i make it like that?

data_l = ['data', 18.8, 18.9, 0.0]
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Fabien
  • 33
  • 1
  • 4

4 Answers4

5

You could create a simple utility function that either converts the given value to a float if possible, or returns it as is:

def maybe_float(s):
    try:
        return float(s)
    except (ValueError, TypeError):
        return s

orig_list = ['data', '18', '17', '0']
the_list = [maybe_float(v) for v in orig_list]

And please don't use names of builtin functions and types such as list etc. as variable names.


Since your data actually has structure instead of being a truly mixed list of strings and numbers, it seems a 4-tuple of (str, float, float, float) is more apt:

data_conv = (data_l[0], *(float(v) for v in data_l[1:]))

or in older Python versions

# You could also just convert each float separately since there are so few
data_conv = tuple([data_l[0]] + [float(v) for v in data_l[1:]]) 
Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
  • Note that your additional comments have shown that you had an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), where the actual problem is hidden by asking about a "solution". Since your data actually looks more like a tuple of `(str, number, number, number)`, you'd not need this kind of solution as presented in this answer, but just `(data_l[0], *[float(v) for v in data_l[1:]])` (in a recent enough version of Python). – Ilja Everilä Aug 30 '17 at 09:50
  • Yes i apologize, i'll pay attention next time, thank you :) – Fabien Aug 30 '17 at 10:05
3

You can use the str.isdigit method and a list comprehension:

list = [int(s) if s.isdigit() else s for s in list]

Here you have a live example

Netwave
  • 40,134
  • 6
  • 50
  • 93
1

Universal approach:

def validate_number(s):
    try:
        return float(s)
    except (ValueError, TypeError):
        return s

data = [validate_number(s) for s in data]

In case the structure is fixed:

data = [s if i == 0 else float(s) for i, s in enumerate(data)]

Another one:

data = [data[0]] + [float(s) for s in data[1:]]

isdigit would work in case of positive integers:

data = [int(s) if s.isdigit() else s for s in data]
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
0

The above-mentioned approaches are working but since a mixed list can also contain an integer value I added an extra checking.

def validate(num):
    try:
        return int(num)
    except (ValueError, TypeError):
        try:
            return float(num)
        except (ValueError, TypeError):
            return num


vals_ = ['cat' ,'s-3-f','7390.19','12']
new_list = [validate(v) for v in vals_]  

Output:

['cat', 's-3-f', 7390.1, 12]
adam shamsudeen
  • 1,752
  • 15
  • 14