2

Consider for example the list in Python containing both strings of letters and numbers

a = ['Total', '1', '4', '5', '2']

How would it be possible to convert this into the mixed value list

b = ['Total', 1.0, 4.0, 5.0, 2.0]

Note that in general we may not know where the letters string will be in the list i.e. we might have

a = ['Total', '1', '4', 'Next', '2']
6
  • Should b[0] always be a string, even if a[0].isdigit() == True? Commented May 27, 2013 at 22:51
  • Or, can you assert that a[0].isdigit() == False? Commented May 27, 2013 at 22:54
  • I was personally looking for a general way to go about it i.e a[3] might have been a string (within the string) also. Commented May 27, 2013 at 23:01
  • Not sure if I follow, could you add an example of that to the question? Commented May 27, 2013 at 23:02
  • 1
    Hopefully the example has cleared that up Commented May 27, 2013 at 23:33

3 Answers 3

5

You can use a generator function and exception handling:

>>> def func(seq):
        for x in seq:
            try:
                yield float(x)
            except ValueError:
                yield x
...             
>>> a = ['Total', '1', '4', '5', '2']
>>> list(func(a))
['Total', 1.0, 4.0, 5.0, 2.0]
Sign up to request clarification or add additional context in comments.

1 Comment

Beat me to it. +1, and a small edit to correct the indentation.
4

Just convert everything but the first column:

b = a[:1] + [float(i) for i in a[1:]]

Judging from your other question you are processing a CSV file, so if the first column is always a string there is no point in converting that part of each row:

>>> a = ['Total', '1', '4', '5', '2']
>>> a[:1] + [float(i) for i in a[1:]]
['Total', 1.0, 4.0, 5.0, 2.0]

You could also use a try: - except ValueError approach, but why incur the overhead when it is known up front what column has text and what columns have numeric values?

Comments

0

Assuming your end goal isn't a csv package, I'd recommend pandas.read_csv.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.