itertools.combination из входного файла csv со списками - PullRequest
2 голосов
/ 05 апреля 2020

У меня есть CSV-файл (out.txt) со следующим форматом

red,green,blue
banana,apple,orange

Я пытаюсь сгенерировать все две комбинации, чтобы вывод выводился в output.csv, как показано ниже

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

Мой код, который работает для одной строки:

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

. Csvdata печатается как

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

Однако, если я вручную определю массив, например,

[1,2,3]

возвращает правильный ответ. Как мне сделать это со списками?

Также, как бы я записал вывод в CSV?

1 Ответ

1 голос
/ 05 апреля 2020

Вам необходимо:

  • читать каждую строку отдельно
  • для каждой строки получить комбинации (я использую itertools.combination ниже)
  • вывести str-представление списка этого itertoools-генератора в одну строку вашего выходного файла (удалив из него ')
  • добавить новую строку
  • сделать это для всех строк

Чтобы получить точный выходной файл, мне пришлось удалить ' значащие строки:

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

Вывод:

# 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]
...