ValueError: could not convert string to float: '[231.49377550490459]' - python

I am trying to cast a python list into a float.
This is the problem narrowed down:
loss = ['[228.55112815111235]', '[249.41649450361379]']
print(float(loss[0]))
And results in the error:
ValueError: could not convert string to float: '[231.49377550490459]'
Can anyone help me?

Strip the brackets.
float(loss[0].replace('[', '').replace(']', ''))

You can use string slicing if there is always just one element in your string list.
loss = ['[228.55112815111235]', '[249.41649450361379]']
print(float(loss[0][1:-1]))

That is because your float value is encapsulated within brackets. And you'll get ValueError because that is not valid float value. In order to convert it, you have to firstly remove them. For example:
>>> my_val = '[228.55112815111235]'
>>> print float(my_val[1:-1])
228.551128151
In your case, you have to write:
>>> loss = ['[228.55112815111235]', '[249.41649450361379]']
>>> float(loss[0][1:-1])
228.55112815111235
In case you want to convert entire list to list of float, you may use map() function as:
>>> map(lambda x: float(x[1:-1]), loss)
[228.55112815111235, 249.4164945036138]

If you want to convert the list values to floats you can use list comprehension:
loss = [float(loss[i][1:-1]) for i in range(len(loss))]
Then your loss list will look like this:
[228.55112815111235, 249.4164945036138]

Related

Python Converting A String to binary then an INT

I am working on an IPV4 breakdown where I have the necessary values in a string variable to represent the binary
(example: 00000000.00000000.00001111.11111111) This is a string
I need a way to turn this string into binary to then properly convert it to it's proper integer value
(in this case 0.0.15.255)
I've seen posts asking about something similar but attempting to apply it to what I'm working on has been unsuccessful
Apologies if this made no sense this is my first time posing a question here
You can achieve this using int() with base argument.
You can know more about int(x,base) - here
Split the string at '.' and store it in a list lst
For every item in lst, convert the item (binary string) to decimal using int(item, base=2) and then convert it into string type.
Join the contents of lst using .
s = '00000000.00000000.00001111.11111111'
lst = s.split('.')
lst = [str(int(i,2)) for i in lst]
print('.'.join(lst))
# Output
0.0.15.255
First split the string on . then convert each to integer equivalent of the binary representation using int builtin passing base=2, then convert to string, finally join them all on .
>>> text = '00000000.00000000.00001111.11111111'
>>> '.'.join(str(int(i, base=2)) for i in text.split('.'))
# output
'0.0.15.255'
You should split the data, convert and combine.
data = "00000000.00000000.00001111.11111111"
data_int = ".".join([str(int(i, 2)) for i in data.split(".")])
print(data_int) # 0.0.15.255
Welcome! Once you have a string like this
s = '00000000.00000000.00101111.11111111'
you may get your integers in one single line:
int_list = list(map(lambda n_str: int(n_str, 2), s.split('.')))

Python array data to integer

I have an array with 4 integer elements for example [1,0,1,0]
I want to convert it into string '1010'
How do that?
I've tried this
b=''.join(str(syndrome_noised.T))
print(b)
but I got '[1,0,1,0]'.
How this string without brackets.
The reason this fails is because you apply str(..) to the matrix. This will generate a single string. This string is however iterable, so you ''.join(..) the characters of that string back together, turning it into the original string again.
What you probably need to do, is convert every single element into a string, and then join these together, like:
b = ''.join(str(x) for x in syndrome_noised.T)
We thus iterate over the elements x in the syndrome_noised.T array, and we each time map it to a str(..), we then join these together.
We can shorten the code a bit, but still have the same semantics, with map:
b = ''.join(map(str, syndrome_noised.T))
syndrome_noised = [1,0,1,0]
''.join(str(x) for x in syndrome_noised)
you could do this by using a for loop like below:
text = str()
for i in array:
text += str(i)
print(text)
and that would return 1010

Python convert tuple values from unicode to str

What is the best way to convert the values in tuples from unicode to string, when the tuples are in a list, can it be done without looping?
unicodedata.normalize('NKFD', x) can only take unicode, not a tuple. The dataset also includes float values.
EXAMPLE
unicode_tuple_list = [(u'text in unicode', u'more unicode'), (u'more text in unicode', u'even more unicode')]
print type(unicode_tuple_list) # list - keep as list
print type(unicode_tuple_list[0]) # tuple - keep as tuple
print type(unicode_tuple_list[0][0]) # unicode
How can all these values be made a str?
I'm not sure there is a way to convert this without using a loop/list comprehension.
I would use the map function to accomplish this, see:
unicode_tuple_list = [(u'text in unicode', u'more unicode'), (u'more text in unicode', u'even more unicode')]
string_tuple_list = [tuple(map(str,eachTuple)) for eachTuple in unicode_tuple_list]
print string_tuple_list
Unpack the tuples, convert to a string and repack.
tuple(map(str, unicode_tuple_list))

could not convert string to float (python)

I am trying to find the sum of all numbers in a list but every time I try I get an error that it cannot convert the string to float. Here is what I have so far.
loop = True
float('elec_used')
while (loop):
totalelec = sum('elec_used')
print (totalelec)
loop = False
You need none of your code above. The while loop is unnecessary and it looks like its just exiting the loop in one iteration i.e. its not used correctly. If you're simply summing all the values in the list:
sum([float(i) for i in elec_used])
If this produces errors, please post your elec_used list. It probably contains string values or blank spaces.
'elec_used' is of type string of characters. You can not convert characters to the float. I am not sure why you thought you could do it. However you can convert the numeric string to float by typecasting it. For example:
>>> number_string = '123.5'
>>> float(number_string)
123.5
Now coming to your second part, for calculating the sum of number. Let say your are having the string of multiple numbers. Firstly .split() the list, type-cast each item to float and then calculate the sum(). For example:
>>> number_string = '123.5 345.7 789.4'
>>> splitted_num_string = number_string.split()
>>> number_list = [float(num) for num in splitted_num_string]
>>> sum(number_list)
1258.6
Which could be written in one line using list comprehension as:
>>> sum(float(item) for item in number_string.split())
1258.6
OR, using map() as:
>>> sum(map(float, number_string.split()))
1258.6

converting a '[1,2,3,4]' to a float or int in python

Hi so I am trying to find the avg of a list
We have to make a function so I have
def avgLst():
'str==>avg of numbers in str'
x=input('Please enter a List: ')
if len(x)==0:
return([])
It is from this point I am having trouble.
I am trying to find to avg of the input we put into the problem.
something like[1,2,3,4] problem is this list is a string because of the input. How do I get the list to be a list of integers or floats to then find the avg of the list?
Thanks,
You can use ast.literal_eval here:
In [6]: strs="[1,2,3,4]"
In [7]: from ast import literal_eval
In [9]: literal_eval(strs)
Out[9]: [1, 2, 3, 4]
help(literal_eval):
In [10]: literal_eval?
Type: function
String Form:<function literal_eval at 0x8cb7534>
File: /usr/lib/python2.7/ast.py
Definition: literal_eval(node_or_string)
Docstring:
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
You can process your input as follows:
def input_to_list(input_str):
input_list = input_str[1:-1].split(",")
return map(int, input_list)
Use literal_eval( ) in ast (Abstract Syntax Trees) module :
>> import ast
>> yrStrList = '[1,2,3,4]'
>> yrList = ast.literal_eval(yrlist)
>> print yrList
[1,2,3,4]
Detail about literal_eval( )
You can handle parsing the string data in numerous ways. I haven't tested this function for speed but one way you could do this is:
def list_avg(str_list):
int_list = [float(i.strip('[]')) for i in str_list.split(',')]
return sum(int_list) / len(int_list)
If I understand correctly what you are asking, then list_avg will return a float average of the integers in str_list.

Categories