python对来自csv的多个字段条目

时间:2018-04-02 22:28:00

标签: python csv text

尝试从这样的csv中获取数据:
col1 col2
eggs sara
bacon john
ham betty

每列中的项目数可能不同,可能不同。 Col1可能有25,col2可能有3.或反过来,或多或少。

循环遍历每个条目,使其输出到像这样的文本文件

breakfast_1
breakfast_item鸡蛋
人sara

breakfast_2
breakfast_item培根 人sara

breakfast_3
breakfast_item火腿
人sara

breakfast_4
breakfast_item鸡蛋
人约翰

breakfast_5
breakfast_item培根 人约翰

breakfast_6
breakfast_item火腿
人约翰

breakfast_7
breakfast_item鸡蛋
人贝蒂

breakfast_8
breakfast_item培根 人贝蒂

breakfast_9
breakfast_item火腿
人贝蒂

因此脚本需要添加“早餐”号码并循环浏览每个breakfast_item和person。 我知道如何创建一个组合但不知道如何在循环中配对每个组合? 有关如何执行此操作的任何提示都非常有用。

3 个答案:

答案 0 :(得分:0)

如果我理解你的问题你可以做这样的事情(从列中获取值后,我猜你知道怎么做):

from itertools import product
with open('file.txt', 'w') as f:
    for i, pair in enumerate(product(your_csv_col1, your_csv_col2)):
        f.write('breakfast_%i\nbreakfast_item %s\nperson %s\n\n' % (i, pair[0], pair[1]))

答案 1 :(得分:0)

我必须指出,通过将输入数据置于不合理的结构中会使问题变得更加困难。 .csv文件中的行意味着行中的数据项之间存在某种连接。但是你正在阅读两个完全独立的领域。那应该是两个文件。但是:

import csv

food_items = []
guests = []
with open('data.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if row['col1']:
            food_items.append(row['col1'])
        if row['col2']:
            guests.append(row['col2'])

breakfast = 0
for guest in guests:
    for food_item in food_items:
        breakfast += 1
        print (f"breakfast_{breakfast}\nbreakfast_item {food_item}\nperson {guest}\n")

编辑:替代print调用Python 2.7或3.5

        print ("breakfast_{0}\nbreafast_item {1}\nperson {2}\n".format(breakfast,food_item,guest))

答案 2 :(得分:0)

首先,明确所有早餐食品。

下面的伪代码

遍历每一行 在2个不同的列表中收集项目和人员 在这两个列表上做一组 说人,物品 Counter = 1 for person in persons: for item in items: Print "breafastitem", Counter Print person, item