I want to convert a certain list of strings into separated lists inside another list, which will contain strings and floats.
I've tried to use the append
method to get the result, but I'm having trouble on making the nested list. Is there a way to get only the last line of my output
as the result? This is my code:
def func(L):
n = []
lists = [i.split(',') for i in L]
for xlist in lists:
xlist[1:] = [float(item) for item in xlist[1:]]
n.append(xlist)
print(n)
if __name__ == '__main__':
func(['PersonX, 10, 92, 70', 'PersonY, 60, 70', 'PersonZ, 98.5, 1100, 95.5, 38'])
OUTPUT: [['PersonX', 10.0, 92.0, 70.0]]
[['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0]]
[['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]
EXPECTED OUTPUT: [['PersonX', 10.0, 92.0, 70.0], ['PersonY', 60.0, 70.0], ['PersonZ', 98.5, 1100.0, 95.5, 38.0]]
Thanks in advance for any help.
CodePudding user response:
We can use some list unpacking and list concatenation to accomplish the result you are looking for:
def func(L):
n = []
for value in L:
a, *b = value.split(',')
n.append([a] [float(item) for item in b])
print(n)
CodePudding user response:
Just unindent the print
outside of the loop to only perform the operation once at the end:
def func(L):
n = []
lists = [i.split(',') for i in L]
for xlist in lists:
xlist[1:] = [float(item) for item in xlist[1:]]
n.append(xlist)
print(n)
Note however that by using print
, you don't really output a list with integers. You should rather use return n