So far all I've been able to find are questions relating to merging lists together.
I'm looking to take 3 lists (2 lists and one 2D list)
list1 = [[1,11,12],[2,21,22],[3,31,32]]
list2 = [4,5,6]
list3 = [7,8,9]
And write these values to a CSV file resulting in the following // Desired Output
Row1,Row2,Row3
1,4,7
2,5,8
3,6,9
11,12 etc shouldn't be written to the CSV file.
Code:
f = open('file.csv', 'wb')
fileWriter = csv.writer(f)
fileWriter.writerow(['Row1', 'Row2', 'Row3']) # Write header row
Attempt:
listlen = len(list2)
list1len = len(list1)
for i in range(listlen):
for j in range(listlen):
for k in range(list1len):
fileWriter.writerow([list1[k][0],list2[i],list3[j]])
Results:
Row1,Row2,Row3
1,4,7
2,4,7
3,4,7
Attempt:
for A,B,C in list1:
for X in list2:
for Y in list3:
tempA = A
tempX = X
tempY = Y
fileWriter.writerow([tempA,tempX,tempY])
Results:
Row1,Row2,Row3
1,4,7
1,4,8
1,4,9
etc.
The current code (both attempts) is iterating through all the values in list2 and list3 for each single digit value in list1. All I've managed to do between the two attempts is change the order of the numbers that are written out.
What I'd like to do is write out the 1st values of each list, then the 2nd etc. to give the desired output.
How could I adjust this to give the desired output / are there better alternatives?
Python 2.7 only
Added the solution I created from Abhijit's answer:
result = zip(zip(*list1)[0], list2, list3)
for row in result:
tempRow = row
fileWriter.writerow(tempRow)