我正在使用Python 3.6。我有三个列表,大约11,000个元素,我转换为csv文件,但由于没有writecolumn()函数,就像有一个writerow(),我的列表显示在无限向右附近。下面是一个示例代码,其中每个示例列表只包含三个元素。如何从列表' number',' session'和' stage'中获取元素。在他们自己的专栏和标题下?为了澄清,我想要所有三个'数字'一列下的元素,以及' session'和'阶段'。
这里的问题接近回答但不完全,所以请不要复制:Write multiple lists into csv. file in Python
我尝试过转换为字典但字典不会在值部分中获取变量。我尝试过迭代,但这只会让每个元素都可以迭代。我尝试过使用zip()函数,但只在一列下按索引对每个列表进行分组。
import csv
import sys
number = ['H. R. 43', 'H. Con. Res. 22', 'S. 11']
session = ['1st Session', '1st Session', '2nd Session']
stage = ['Introduced in House', 'Engrossed in House', 'Referred in Senate']
def main(anything):
global number
global session
global stage
with open('BILLS.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Number', 'Session', 'Stage'])
writer.writerow(number)
writer.writerow(session)
writer.writerow(stage)
if __name__ == '__main__':
main(sys.argv)
答案 0 :(得分:0)
from itertools import zip_longest
combine_three_list = zip_longest(number, session, stage)
答案 1 :(得分:0)
由于每个列表中的元素数量相同,因此可以使用zip
。
import csv
import sys
number = ['H. R. 43', 'H. Con. Res. 22', 'S. 11']
session = ['1st Session', '1st Session', '2nd Session']
stage = ['Introduced in House', 'Engrossed in House', 'Referred in Senate']
def main():
global number
global session
global stage
with open('BILLS.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Number', 'Session', 'Stage'])
for ele in list(zip(number, session, stage)):
writer.writerow(ele)
if __name__ == '__main__':
main()
答案 2 :(得分:0)
您可以使用zip
功能
import csv
number = ['H. R. 43', 'H. Con. Res. 22', 'S. 11']
session = ['1st Session', '1st Session', '2nd Session']
stage = ['Introduced in House', 'Engrossed in House', 'Referred in Senate']
# setting newline to '' is required because csv will add blank line
with open('BILLS.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Number', 'Session', 'Stage'])
writer.writerows(zip(number, session, stage))
或者您可以使用pandas
模块
import pandas as pd
number = ['H. R. 43', 'H. Con. Res. 22', 'S. 11']
session = ['1st Session', '1st Session', '2nd Session']
stage = ['Introduced in House', 'Engrossed in House', 'Referred in Senate']
#building a dictionary out of your lists
data = {'number':number, 'session':session, 'stage':stage}
df = pd.DataFrame.from_dict(data)
#pandas even has a buildin to_csv() function
#with open('BILLS.csv', 'w') as f:
# df.to_csv(f)
您还应停止使用global
变量