简体   繁体   中英

python pair multiple field entries from csv

Trying to take data from a csv like this:
col1 col2
eggs sara
bacon john
ham betty

The number of items in each column can vary and may not be the same. Col1 may have 25 and col2 may have 3. Or the reverse, more or less.

And loop through each entry so its output into a text file like this

breakfast_1
breakfast_item eggs
person sara

breakfast_2
breakfast_item bacon
person sara

breakfast_3
breakfast_item ham
person sara

breakfast_4
breakfast_item eggs
person john

breakfast_5
breakfast_item bacon
person john

breakfast_6
breakfast_item ham
person john

breakfast_7
breakfast_item eggs
person betty

breakfast_8
breakfast_item bacon
person betty

breakfast_9
breakfast_item ham
person betty

So the script would need to add the "breakfast" number and loop through each breakfast_item and person. I know how to create one combo but not how to pair up each in a loop? Any tips on how to do this would be very helpful.

If I understand your question correctly you can do something like this (After you get values from columns, I guess you know how to do that):

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]))

I have to point out that your problem is made more difficult by having your input data in an unreasonable structure. A row in a .csv file implies that there is some connection between the data items in the row. But you are reading in two entirely separate domains. That should be two files. However:

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")

Edit: alternative print call for Python 2.7 or 3.5

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

First, get a distinct of all breakfast items.

A pseudo code like below

Iterate through each line Collect item and person in 2 different lists Do a set on those 2 lists Say persons, items Counter = 1 for person in persons: for item in items: Print "breafastitem", Counter Print person, item

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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