5

I have a list which looks something like this:

['1', '2', '3.4', '5.6', '7.8']

How do I change the first two to int and the three last to float?

I want my list to look like this:

[1, 2, 3.4, 5.6, 7.8]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Johan Fall
  • 67
  • 1
  • 1
  • 2

6 Answers6

15

Use a conditional inside a list comprehension

>>> s = ['1', '2', '3.4', '5.6', '7.8']
>>> [float(i) if '.' in i else int(i) for i in s]
[1, 2, 3.4, 5.6, 7.8]

Interesting edge case of exponentials. You can add onto the conditional.

>>> s = ['1', '2', '3.4', '5.6', '7.8' , '1e2']
>>> [float(i) if '.' in i or 'e' in i else int(i) for i in s]
[1, 2, 3.4, 5.6, 7.8, 100.0]

Using isdigit is the best as it takes care of all the edge cases (mentioned by Steven in a comment)

>>> s = ['1', '2', '3.4', '5.6', '7.8']
>>> [int(i) if i.isdigit() else float(i) for i in s]
[1, 2, 3.4, 5.6, 7.8, 100.0]
Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
6

Use a helper function:

def int_or_float(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

Then use a list comprehension to apply the function:

[int_or_float(el) for el in lst] 
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
6

Why not use ast.literal_eval?

import ast

[ast.literal_eval(el) for el in lst]

Should handle all corner cases. It's a little heavyweight for this use case, but if you expect to handle any Number-like string in the list, this'll do it.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
1

Use isdigit method of string:

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

or with map:

numbers = map(lambda x: int(x) if x.isdigit() else float(x), numbers)
Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
1
def st_t_onumber(x):
    import numbers
    # if any number
    if isinstance(x,numbers.Number):
        return x
    # if non a number try convert string to float or it
    for type_ in (int, float):
        try:
            return type_(x)
        except ValueError:
            continue

l = ['1', '2', '3.4', '5.6', '7.8']

li = [ st_t_onumber(x) for x in l]

print(li)

[1, 2, 3.4, 5.6, 7.8]
LetzerWille
  • 5,355
  • 4
  • 23
  • 26
0

If you want to display as the same list append the list by using the following query:

item = input("Enter your Item to the List: ")
shopList.append(int(item) if item.isdigit() else float(item))

Here when the user enters int values or float values it appends the list shopList and stores these values in it.

Chippy
  • 33
  • 1
  • 5