简体   繁体   中英

itertools.combination from input file csv with lists

I have a CSV file (out.txt) with the following format

red,green,blue
banana,apple,orange

I am trying to generate all two combinations so that the output is put to output.csv like the following

[red,green][red,blue][green,blue]
[banana,apple][banana,orange][apple,orange]

My code that works for single line is

import csv

with open('out.txt', newline='') as csvfile:
    csvdata = list(csv.reader(csvfile))

print(csvdata)

r = 2; 
n = len(csvdata); 
print(n)

def printCombination(csvdata, n, r): 
    data = [0]*r; 
    print (data)

    combinationUtil(csvdata, data, 0,  
                    n - 1, 0, r); 

def combinationUtil(csvdata, data, start,  
                    end, index, r): 

    if (index == r): 
        for j in range(r): 
            print(data[j], end = " "); 
        print(); 
        return; 

    i = start;  
    while(i <= end and end - i + 1 >= r - index): 
        data[index] = csvdata[i]; 
        combinationUtil(csvdata, data, i + 1,  
                        end, index + 1, r); 
        i += 1; 

printCombination(csvdata, n, r); 

The csvdata prints as

[['red', 'green', 'blue'], ['banana', 'apple', 'orange']]

However, if I manually define an array like so

[1,2,3]

it returns the correct answer. How do I do this with lists?

Also how would I write the output to a csv?

You need to:

  • read each line seperately
  • for each line get the combinations (I am using itertools.combinations below)
  • print the str-representation of the list of that itertoools-generator into one line of your output file (removing ' from it)
  • add a newline
  • do that for all lines

To get to your exact output file, I had to remove the ' signifying strings:

with open ("data.txt","w") as f:
    f.write("red,green,blue\nbanana,apple,orange")

# store each line as list of words seperately    
lines = []
with open("data.txt") as f:
    for l in f:
        l = l.strip() # remove \n
        if l:
            lines.append( list(w.strip() for w in l.split(",")))

print(lines) # [['red', 'green', 'blue'], ['banana', 'apple', 'orange']]

from itertools import combinations

with open("result.txt", "w") as f:
    for l in lines:
        for c in combinations(l,2):
            f.write(str(list(c)).replace("'","")) # remove the ' of strings
        f.write("\n")

print(open("result.txt").read())

Output:

# what was read into `lines` from the file
[['red', 'green', 'blue'], ['banana', 'apple', 'orange']]

# output for 'result.txt' 
[red, green][red, blue][green, blue]
[banana, apple][banana, orange][apple, orange]

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