Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list of strings into floats/ints in F#

Tags:

f#

c#-to-f#

Is there a quick and simple way to convert an entire list of strings into floats or integers and add them together similar to this in F#?

foreach(string s in list)
{
    sum += int.Parse(s);
}
like image 236
Jacco Avatar asked Dec 29 '13 12:12

Jacco


People also ask

How do I convert a list of strings to list floats?

The most Pythonic way to convert a list of strings to a list of floats is to use the list comprehension floats = [float(x) for x in strings] . It iterates over all elements in the list and converts each list element x to a float value using the float(x) built-in function.

Can you convert strings to floats?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

How do you convert a list of strings to a list of ints in Python?

To convert a list of strings to a list of integers: Pass the int() class and the list to the map() function. The map() function will pass each item of the list to the int() class. The new list will only contain integer values.

How do you convert a string to an int or a float?

In Python, you can convert a string str to an integer int and a floating point number float with int() and float() . This article describes the following contents. Use str() to convert an integer or floating point number to a string. You can also convert a list of strings to a list of numbers.


1 Answers

If you want to aim for minimal number of characters, then you can simplify the solution posted by Ganesh to something like this:

let sum = list |> Seq.sumBy int

This does pretty much the same thing - the int function is a generic conversion that converts anything to an integer (and it works on strings too). The sumBy function is a combination of map and sum that first projects all elements to a numeric value and then sums the results.

like image 142
Tomas Petricek Avatar answered Jan 08 '23 00:01

Tomas Petricek