I have tried using this code below but it keeps giving me Type Error : float expected to only have one argument, got 2. I want to convert the nested list which contains strings to a float so that I am able to calculate the sum of p and q. After many hours of trying and researching online I am still stuck.
C1=[['1','2'],['1','2']]
int1=[]
for p, q in C1:
int1.append(float(p, q))
CodePudding user response:
I think your difficulty here is that you are using float
on two values, rather than one. You probably want:
C1 = [['1','2'],['1','2']]
int1 = []
for p, q in C1:
int1.append([float(p), float(q)])
which will give you a list of lists of floats. To get a list of the sums of the floats, modify this a bit further:
C1 = [['1','2'],['1','2']]
int1 = []
for p, q in C1:
int1.append(float(p) float(q))
if you instead wanted to sum all of the values, you can then just sum the list:
total = sum(int1)
CodePudding user response:
The built-in float() function only takes one argument.
You can build your target list like this:
C1 = [['1','2'],['1','2']]
int1 = [[float(n) for n in e] for e in C1]
print(int1)
Output:
[[1.0, 2.0], [1.0, 2.0]]
Doing it like this means that you're not constrained by the length of the input list or its sub-lists
CodePudding user response:
in here you can use multiple way to solve this problem in small scale you can create a new list and convert each value to float and append it to new list ... but in large scale like a list with 2-000-000 or more length maybe you make mistake and got a memory issue best way to solve this is change value's in actual list
as you know list are pass by refrense it's mean they send there location in memory and when you copy them and change copy version it's effect on real list to
so in here i'm solve this using this ability in python
In [15]: for index,value in enumerate(C1):
...: for inner_index, inner_value in enumerate(C1[index]):
...: C1[index][inner_index]=float(inner_value)
...: print(C1)