简体   繁体   English

使用两个列表写入csvFile。 如何将每个列表写到两个不同的列

[英]Writing to a csvFile using two lists. How do i write each list to two different columns

I can write the first list of items to go down the first column how i want it but im struggling to get the second list to write to the third[2] column in the csv file. 我可以按照自己的意愿写第一个项目列表,以使第一列下降,但是我很难使第二个列表写入csv文件中的第三[2]列。 This i what i currently have. 这是我目前拥有的。 This just writes the second list below the first as i have just repeated the action of the first list. 这只是将第二个列表写在第一个列表之下,因为我刚刚重复了第一个列表的操作。

firstHalf = ["Dad", "Mom", "nan"]
secondHalf = ["Brother", "Sister", "Cousin"]
    with open('MyFile.csv', 'w', newline='') as csv_file:
        csv_app = csv.writer(csv_file, delimiter=',')
        for player in firstHalf:
            csv_app.writerow([player])
        for player1 in secondHalf:
            csv_app.writerow([player1])

This currently writes this to the csv file with all the elements of both list down the first[0] column. 当前,这会将其写入csv文件,并且这两个元素的所有元素都在first [0]列中列出。 i want the first list down the first column but second list down the third column. 我希望第一列在第一列下,但第二列在第三列下。

Iv played around this a few things but struggling to get it how i want in the csv file. iv围绕这件事玩了一些,但是却很难在csv文件中得到它。

Take a look at the zip function. 看一下zip功能。

firstHalf = ["Dad", "Mom", "nan"]
secondHalf = ["Brother", "Sister", "Cousin"]

with open('text.csv', 'w', newline='') as file:
    csv_app = csv.writer(file, delimiter=',')
    for one, two in zip(firstHalf, secondHalf):
        csv_app.writerow([one, None, two])

Mind, that your lists should be of the same length. 请注意,您的列表应具有相同的长度。

暂无
暂无

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

相关问题 比较两个列表的长度。 他们为什么不同? - Comparing the lengths of two lists. Why are they different? 如何制作一个递归函数,返回给定两个列表的相同索引的总和列表。? - How can I make a recursive function that returns a list of sum of the same index given two lists.? CSV文件列中的对象是列表。 如何使用Python将它们组合成一个巨型列表? - Objects in column of csv file are lists. How do I combine these into one giant list using Python? 如何按列表中的两个不同值对列表进行排序? - How do I sort lists by two different values within that list? 两个列表上的 Python Itertools。 从每个列表中获取超过 1 个值 - Python Itertools on two lists. Get more then 1 value from each list 将两个列表写入 python 中 csv 文件中的两个不同列 - Write two lists to two different columns in a csv file in python CSV 列有列表列表。 如何将此列转换为具有 sqlite 的关系数据库? - CSV column has list of lists. How do I turn this column into a relational database with sqlite? 如何使用熊猫分解两列不同长度的列表 - How to explode two columns of lists with different length using pandas 如何编写一个 Function 计算两列不同大小的相同和不同 ID - How Do I Write A Function That Counts Identical and Different IDs in Two Columns of Different Sizes 使用python比较两个列表。 为什么Python将第一个列表的第一个数字与第二个列表的所有数字进行比较? - Using python to compare two lists. Why Python compares the first number of the first list with all the numbers of the second list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM