1

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)

1 Answer 1

2

Assuming you are already aware, to write a csv , and the part you might be wondering is an elegant way to access the data.

A nifty way to access the data is use the built-in zip. zip([iterable, ...]) has the elegant ability to transpose data, and that what you would need here

>>> zip(zip(*list1)[0], list2, list3)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

Unfortunately, the target result you are contemplating is a formatted data rather than a csv, so even if you are writing the csv as a tab delimited, the result may not be desirable

>>> result = [['row1','row2','row3']] + zip(zip(*list1)[0], list2, list3)
>>> with open('file.csv', 'wb') as fin:
    writer = csv.writer(fin, delimiter = '\t')
    writer.writerows(result)

row1    row2    row3
1   4   7
2   5   8
3   6   9

One option is to forego the idea of csv and instead write the data as a formatted string using str.format.

>>> header = ['row1','row2','row3']
>>> result = zip(zip(*list1)[0], list2, list3)
>>> format_string = "{:<10}{:<10}{:<10}"
>>> with open('file.csv', 'wb') as fin:
    fin.write(format_string.format(*header))
    fin.write('\n')
    for row in result:
        fin.write(format_string.format(*row))
        fin.write('\n')


row1      row2      row3      
1         4         7         
2         5         8         
3         6         9     
Sign up to request clarification or add additional context in comments.

3 Comments

Looking at what I need to do again, it's fine to have the output as a proper comma delineated list. I've adjusted the question accordingly. going to go and try this now.
zip was indeed an elegant solution; I've added the final solution I came up with to the question
@Simon: You don;t need a loop, if you are using writer.writerows

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.