OreoDog
OreoDog

Reputation: 11

Converting a List Into Float Variables

I'm wanting to take an input as a list but use each variable as a float. Is there a simpler way to make this conversion other than explicitly like I do below, as a list is defined with strings, and I want to, for example, add rather than concatenate:

edges = input("Enter three edges: ").split(", ")  
print("The perimeter is", (float(edges[0]) + float(edges[1]) + float(edges[2])))

Upvotes: 0

Views: 63

Answers (3)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160417

You could use map to transform to floats and then sum to sum them up:

print("The perimeter is", sum(map(float, edges)))

map takes a callable (float here), and applies it to every element of an iterable (edges here). This creates a map iterator (something that can be iterated through) that is then supplied to sum which sums it up.

Then you print it.

You could of course create an ugly little expression that combines them all together because both input and split return their results:

print("Sum is ", sum(map(float, input('Enter three edges ' ).split(","))))

but don't, it's ugly.

Upvotes: 1

John1024
John1024

Reputation: 113834

Since you probably want the edges only as numbers, you can convert them early:

edges = [float(edge) for edge in input("Enter three edges: ").split(", ")]
print("The perimeter is", sum(edges))

Sample run:

Enter three edges: 1.2, 3.4, 5.6
The perimeter is 10.2

Upvotes: 0

Yoav Glazner
Yoav Glazner

Reputation: 8066

map is your friend

sum(map(float, edges))

or a generator expression

sum(float(f) for f in edges)

Have fun!

Upvotes: 1

Related Questions