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);
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With