【问题标题】:itertools.combination from input file csv with lists来自输入文件 csv 和列表的 itertools.combination
【发布时间】:2020-04-05 12:40:20
【问题描述】:

我有一个 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 ?

【问题讨论】:

  • 您发布的代码充满了IndentationError's - 请edit 修复它
  • 还有为什么是';'在每一行的末尾?好的,但不是流行的 Python 风格。
  • 希望修复代码。对不起,我是一个完整的初学者,我会阅读这个。我主要来自 PHP 背景。

标签: python list combinations itertools


【解决方案1】:

你需要:

  • 分别读取每一行
  • 为每一行获取组合(我在下面使用itertools.combinations
  • 将该 itertools-generator 列表的 str 表示形式打印到输出文件的一行中(从中删除 ')
  • 添加换行符
  • 对所有行都这样做

要获得您的确切输出文件,我必须删除 ' 表示字符串:

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]

【讨论】:

  • 哇,这就是我想要的。
  • 还有一个问题。如果 result.txt 包含一些重复项,例如 [red, green][red, blue][green, blue] [apple, orange][red, green][red,blue][red.purple] - 注意 [red,green ] 重复。我将如何删除 [red,green] 或仅获得唯一值?
  • @Sam 使用上面的代码你不会得到任何重复,除非你在你的输入中得到相同的值。该代码不考虑“其他输入行” - 调整此代码以从输入中删除重复值可以使用集合或其他东西来完成,但是您也将删除“红色,绿色,蓝色,红色”第二个红色值- 你必须以某种方式从lines 的内部列表中删除被欺骗的值 - 有很多关于从列表中删除重复的帖子 - fe this
  • 您将不得不相互测试多行,这使得它变得更加困难 - 尽力而为或提出一个新问题,专注于该问题以及您在研究后碰巧实现了什么
猜你喜欢
  • 2016-07-09
  • 1970-01-01
  • 1970-01-01
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
相关资源
最近更新 更多