1

Hi I am quite new to python and what I want to do is simple but I just can't seem to get around it.

I have a simple array as shown below:

A1 = [('1.000000', '4.000000'), ('2.000000', '5.000000'), ('3.000000', '6.000000'), ('1.000000', '4.000000'), ('2.000000', '5.000000'), ('3.000000', '6.000000')]

I want to change all elements within the array into floats so I can do calculations on them (such as sum etc.). The end results should look something like this:

A2 = [(1.000000, 4.000000), (2.000000, 5.000000), (3.000000, 6.000000), (1.000000, 4.000000), (2.000000, 5.000000), (3.000000, 6.000000)]

I have tried the following:

A2 = [float(i) for i in A1]

however I get the error:

TypeError: float() argument must be a string or a number

Could anyone point me towards a solution.

Thanks in advance

1
  • 1
    i in your case is a tuple with 2 floats that's why you get the exception. Commented Oct 1, 2014 at 7:10

3 Answers 3

2

Here's one pretty simple way:

>>> [map(float, x) for x in A1]
[[1.0, 4.0], [2.0, 5.0], [3.0, 6.0], [1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]

I like it's because it's short (some would say terse) and since using map() makes it not hardcode or be explicit about the expected format of each x, it just says that it assumes A1 to be a list of sequences.

I have no idea how this compares performance-wise to other solutions (such as the more explicit [(float(x), float(y) for (x, y) in A1] seen below).

Sign up to request clarification or add additional context in comments.

Comments

2

Each element of A1 is a tuple ('1.000000', '4.000000'). You will have to convert each item of the tuple:

A2 = [(float(i), float(j)) for (i, j) in A1]

2 Comments

@iksalglam If you know that the inner tuples have exactly 2 elements in them, this would be the normal answer.
Thank you works great!!! But I think it would only work for tuples where I know I have two elements
1

You need to iterate over the inner tuples as well.

A2 = [tuple(float(s) for s in i) for i in A1]

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.