Here's a simple example:
def separateFloatInt(L):
l1=list()
l2=list()
for x in L:
if type(x)==int:
l1.append(x)
else:
l2.append(x)
return l1,l2
L=['2', '3.5', '6', '5.1', '9.8', '7.8', '5', '3.3', '0.5', '9']
integer,reel=separateFloatInt(L)
How can I separate one list into two list, one has only integers, the other has only floats?
CodePudding user response:
Try:
def separateFloatInt(L):
l1, l2 = [], []
for v in L:
try:
l1.append(int(v))
except ValueError:
l2.append(float(v))
return l1, l2
L = ["2", "3.5", "6", "5.1", "9.8", "7.8", "5", "3.3", "0.5", "9"]
integer, reel = separateFloatInt(L)
print(integer)
print(reel)
Prints:
[2, 6, 5, 9]
[3.5, 5.1, 9.8, 7.8, 3.3, 0.5]
CodePudding user response:
Thank you for your help
I developped this solution as well.
def separateFloatInt(L):
L=[float(x) for x in L]
L=[str(x) for x in L]
l1=list()
l2=list()
for x in L:
print(x)
a,b=x.split(".")
if int(b)!=0:
l1.append(x) # float
else:
l2.append(x) # int
return l1,l2
p=read()
print(p)
real,integer=separateFloatInt(p)
Output for:
L=['2', '3.2', '6', '3.5', '8.4', '8.8', '9', '5', '4.1', '5']
Is
print(real)
print(integer)
['3.2', '3.5', '8.4', '8.8', '4.1']
['2.0', '6.0', '9.0', '5.0', '5.0']