Converting list with 1 variable to float in Python - python

I have a list variable with one element,
x=['2']
and I want to convert it to a float:
x=2.0
I tried float(x), or int(x) - without success.
Can anyone please help me?

You need to convert the first item in your one-item list to a float. The approaches you tried already are trying to convert the whole list to a float (or an int - not sure where you were going with that!).
Python is zero-indexed (index numbers start from zero) which means that the first item in your list is referred to as x[0].
So the snippet you need is:
x = float(x[0])

Related

Removing single quotes from the list in python to find the minimum value [duplicate]

This question already has answers here:
How do I parse a string to a float or int?
(32 answers)
Closed 6 months ago.
I have a list with the following entries. How can I remove the single quotes for each entries in the list? I need to find the minimum value in the list. When I used min function, result is wrong due to the single quotes in the list. I know the workaround will be, making a script to save the minimum at each loop. But is there any other way to remove the single quotes, which makes the process simpler?
['-406', '-140', '-141', '-66.', '-135', '-142', '-136','-0.01']
The below list is derived from a text file having lot of strings and after using split only Iam getting the single quotes. Can I do something there to avoid the single quotes?
Thanks
You have an array of strings. You can use float or other variants to convert a string to numeric. And then you can call min function on the numeric list.
a= ['-406', '-140', '-141', '-66.', '-135', '-142', '-136','-0.01']
b = [float(i) for i in a]
# gives b as
[-406.0, -140.0, -141.0, -66.0, -135.0, -142.0, -136.0, -0.01]
c = min(b)
# c is
-406.0
The result is wrong because the values are strings, not because of the single quotes - those are just there in your output to signify that they're strings and lists.
You can convert the values to floats using float, and then use min on the result:
lowest_value = min(map(float, your_list))
map applies the float conversion to every element in the list, then min retrieves the lowest value from the returned iterator.

Python | Convert hexstrings in a list to float

I have data-points of hex-strings in a list.
I tried converting the list to string and then to a byte array. As I try to convert the byte array to float it only returns one value.
Code used is :
byteArrObj = bytearray(n, 'utf-8')
byteObj = bytes(byteArrObj)
byte8=bytearray.fromhex(b)
print(byte8)
floatvalue = struct.unpack('<f', byte8[:4])
This produces a tuple, like `(0.09273222088813782,).
How do I print all the float values from the list?
First, let's make a function that converts one of the values:
def hexdump_to_float(text):
return struct.unpack('<f', bytes.fromhex(text))[0]
Notice:
I skip the step of finding byteArrObj or byteObj from your code, because they had no effect in your code and do not help solve the problem.
I use the type bytes rather than bytearray because we don't need to modify the underlying data. (It's analogous to using a tuple rather than list.)
I do not bother with slicing the data, because we already know there will be only 4 bytes, and because struct.unpack would ignore any extra data in the buffer anyway.
To get the value out of the tuple that struct.unpack returns, I simply index into the tuple. That gives me a single float value.
So this is a simple one-line function, but it helps to make a function anyway since it gives a clear name for what we are doing.
The next step is to apply that to each element of the list. You can do this easily with, for example, a list comprehension:
my_floats = [hexdump_to_float(x) for x in my_hexdumps]

How to select a list element and convert it to "float"?

So, I'm currently in the middle of a Python exercise, and I'm struggling with something. I have to make a multiplication between two variables, a and X, but I select a inside a list, and a is returned as a list with a single element (for example [0.546] instead of 0.546.)
I'd like to convert it into a float element (so 0.546, without the brackets, in my example), but float() doesn't accept a list as an argument. It's probably simple to do, but I'm kind of a Python beginner, and I can't find the answer I want on the Internet (it doesn't help that I'm French.)
Here's my code :
for (i,individual) in iris.iterrows():
if pd.isnull(individual["petal_width"]):
a = coeffs["case 1"]['a'] #here I want to select the element 'a' as a float
b = coeffs["case 1"]['b'] #same thing for b
X = individual["petal_length"]
Y = a*X + b
By using different print commands, I know that X is a float, so the problem comes from a and b.
Also, when I want to do the multiplication, it says "can't multiply sequence by non-int of type float"
Thanks in advance for any help, cheers!
Just wrap the variable in with float, like this:
a = float(coeffs["case 1"]['a'])
if you want to convert a whole list, not a dict, then you can do this:
my_float_list = [float(x) for x in my_list]
or
my_float_list = list(map(float, my_list))
EDIT: Seems like coeffs["case 1"]['a'] is a list of floats, then do this:
# if you are sure that there is atleast one
a = coeffs["case 1"]['a'][0] # if you are sure that there is atleast one value
# if you are unsure that there is atleast one
a = coeffs["case 1"]['a'][0] if len(coeffs["case 1"]['a']) > 0 else 1.0

python struct.pack(): pack multiple datas in a list or a tuple

Say i have a list or a tuple containing numbers of type long long,
x = [12974658, 638364, 53637, 63738363]
If want to struct.pack them individually, i have to use
struct.pack('<Q', 12974658)
or if i want to do it as multiple, then i have to explicitly mention it like this
struct.pack('<4Q', 12974658, 638364, 53637, 63738363)
But, how can i insert items in a list or tuple inside a struct.pack statement. I tried using for loop like this.
struct.pack('<4Q', ','.join(i for i in x))
got error saying expected string, int found, so i converted the list containing type int into str, now it gets much more complicated to pack them. Because the whole list gets converted into a string( like a single sentence).
As of now im doing some thing like
binary_data = ''
x = [12974658, 638364, 53637, 63738363]
for i in x:
binary_data += struct.pack('<Q', i)
And i unpack them like
struct.unpack('<4Q', binary_data)
My question: is there a better way around, like can i directly point a list or tuple inside the struct.pack statement, or probably a one liner ?
You can splat, I'm sorry "unpack the argument list":
>>> struct.pack("<4Q", *[1,2,3,4])
'\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00'
If the length of the list is dynamic, you can of course build the format string at runtime too:
>>> x = [1, 2] # This could be any list of integers, of course.
>>> struct.pack("<%uQ" % len(x), *x)
'\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00'

problem with list return type?

my list has value such as
m=[['na','1','2']['ka','31','45']['ra','3','5']
d=0
r=2
t=m[d][r]
print t # this is givin number i.e 2
Now when I use this value
u=[]
u=m[t]
I am getting an err msg saying type error list does take str values...
i want to use like this how can i convert that t into a integer??
please suggest..
thanks..
Your problem is that you can't index into a list using a string. To convert t to an integer use int:
u=m[int(t)]
Use int(t) as the index, not t itself, since t is a string and to index a variable you need an integer, not a string, as the error message is telling you.

Categories

Resources