I need to turn this lists of lists into the following format. I accomplished this by creating a function and creating 4 additional lists to split the data into the required format. I was wondering if this could resolved in a simpler way.
The code I wrote is at the end.
Thanks.
values =
[[100000.0, 36.0, 0.08, 20000.0],
[200000.0, 12.0, 0.1, 0.0],
[628400.0, 120.0, 0.12, 100000.0],
[4637400.0, 240.0, 0.06, 0.0],
[42900.0, 90.0, 0.07, 8900.0],
[916000.0, 16.0, 0.13, 0.0],
[45230.0, 48.0, 0.08, 4300.0],
[991360.0, 99.0, 0.08, 0.0],
[423000.0, 27.0, 0.09, 47200.0]]
This needs to be converted to column format as such:
[[100000.0, 200000.0, 628400.0, 4637400.0, 42900.0, 916000.0, 45230.0, 991360.0, 423000.0]
,[36.0, 12.0, 120.0, 240.0, 90.0, 16.0, 48.0, 99.0, 27.0]
,[0.08, 0.1, 0.12, 0.06, 0.07, 0.13, 0.08, 0.08, 0.09]
,[20000.0, 0.0, 100000.0, 0.0, 8900.0, 0.0, 4300.0, 0.0, 47200.0]]
def all_list(value):
result = {}
amount = []
duration = []
rate = []
down_payment = []
headers = parse_headers(file1[0])
total = [amount, duration, rate, down_payment]
for v in range(0,len(value)):
amount.append(value[v][0])
duration.append(value[v][1])
rate.append(value[v][2])
down_payment.append(value[v][3])
for k,v in zip(total, headers):
result[v] = k
return result
CodePudding user response:
You are basically trying to transpose the 2-dimensional list. Here is an implementation to this.
def transpose(l1):
l2 = []
for i in range(len(l1[0])):
row =[]
for item in l1:
row.append(item[i])
l2.append(row)
return l2
CodePudding user response:
Use zip
with the *
operator:
>>> values = [[100000.0, 36.0, 0.08, 20000.0],
... [200000.0, 12.0, 0.1, 0.0],
... [628400.0, 120.0, 0.12, 100000.0],
... [4637400.0, 240.0, 0.06, 0.0],
... [42900.0, 90.0, 0.07, 8900.0],
... [916000.0, 16.0, 0.13, 0.0],
... [45230.0, 48.0, 0.08, 4300.0],
... [991360.0, 99.0, 0.08, 0.0],
... [423000.0, 27.0, 0.09, 47200.0]]
>>> list(zip(*values))
[(100000.0, 200000.0, 628400.0, 4637400.0, 42900.0, 916000.0, 45230.0, 991360.0, 423000.0), (36.0, 12.0, 120.0, 240.0, 90.0, 16.0, 48.0, 99.0, 27.0), (0.08, 0.1, 0.12, 0.06, 0.07, 0.13, 0.08, 0.08, 0.09), (20000.0, 0.0, 100000.0, 0.0, 8900.0, 0.0, 4300.0, 0.0, 47200.0)]
CodePudding user response:
There is a more concise way of doing it using comprehensions:
amount = [item[0] for item in value]
duration = [item[1] for item in value]
rate = [item[2] for item in value]
down_payment = [item[3] for item in value]
CodePudding user response:
This is a matrix transpose. Numpy has this built in like this
import numpy as np
ans = np.transpose(values)