Reputation: 3
I am new to python. I have a list as below.
1 [2,3,4] 10
2 [3,4] 20
3 [4] 30
Then, I want to make the 2nd column above of elements become the 1st column below and calculate the 2nd column below by the last column above divided by the total elements in the 2nd column as below.
2 10/3
3 10/3
4 10/3
3 20/2
4 20/2
4 30/1
Upvotes: 0
Views: 50
Reputation: 170
First you will need to reformat your data into a bit more usable format. I'll include some extra steps so it makes more sense as to how it all works together.
input_list = [] ### initializes the list you'll be using (otherwise you have no list to add to)
row_1 = [1,[2,3,4], 10]
row_2 = [2,[3,4], 20]
row_3 = [3,[4], 30]
input_list.append(row_1)
input_list.append(row_2)
input_list.append(row_3)
This will result in all your data being assigned to input_list
like so,
input_list = [[1,[2,3,4], 10], [2,[3,4], 20], [3,[4], 30]]
which can now be used to iterate through to get the answers you are looking. You can of course, skip defining each row as it's own variable and then appending each to input_list
by just defining input_list
with all of your data in one step. But for the sake of readability and understanding everything that's going on, I used the step by step approach above. Now by creating a function with the input_list
as a parameter, you can create two simple loops (one within the other) to do what you need,
def operation(input):
output = [] ### initializes your final output list variable
for row in input:
for number in row[1]:
column1 = row[0]
column2 = number
column3 = row[2]/len(row[1])
output.append([column1, column2, column3])
return output
And then to actually create the output you need, call the operation
function with input_list
as the parameter,
output_list = operation(input_list)
where output_list
is a newly defined variable that will be assigned to whatever the operation
function returns (your output).
To then see the list in a readable format, run this as well,
for row in output_list:
print row
This should give you what you are looking for!
Upvotes: 1