简体   繁体   English

Python,使用多个列表中的列将新行写入CSV

[英]Python, Write new line to CSV using columns from multiple lists

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) 我正在寻找3个清单(2个清单和一个2D清单)

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 并将这些值写入CSV文件,产生以下// 所需的输出

Row1,Row2,Row3 
1,4,7 
2,5,8
3,6,9

11,12 etc shouldn't be written to the CSV file. 11,12等不应该写入CSV文件。

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. 当前代码(两次尝试)正在遍历list2和list3中的所有值,以获取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 仅Python 2.7

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)

Assuming you are already aware, to write a csv , and the part you might be wondering is an elegant way to access the data. 假设您已经知道编写csv,并且您可能想知道的部分是访问数据的一种优雅方式。

A nifty way to access the data is use the built-in zip . 访问数据的一种不错的方法是使用内置的zip zip([iterable, ...]) has the elegant ability to transpose data, and that what you would need here zip([iterable, ...])具有出色的数据转置能力,您将在这里需要

>>> 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 不幸的是,您正在考虑的目标结果是格式化数据而不是csv,因此即使您将csv写为制表符分隔的标签,结果可能也不理想

>>> 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 . 一种选择是放弃csv的想法,而是使用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     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM