简体   繁体   English

使用itertools.groupby

[英]Using itertools.groupby

I have a file like this: 我有一个像这样的文件:

1     abc
1     def
2     ghi
3     jkl
3     mno
3     pqr

And want to generate a file like this from it: 并希望从中生成这样的文件:

abc;def
jkl;mno
jkl;pqr
mno;pqr

I have the following code: 我有以下代码:

with open('input.txt') as f1:
with open("output.csv", "wb") as f2:
    cw = csv.writer(f2, delimiter=";")
    for l in itertools.groupby((l.split() for l in f1), lambda x: x[0]):
        grouped = set(x[1] for x in l[1])  # set avoids duplicate rows
        for c in itertools.combinations(grouped, 2):
            cw.writerow(c)

But this code does not write anything to the output file. 但是此代码不会将任何内容写入输出文件。 What am I doing wrong? 我究竟做错了什么?

Using csv.writer to insert ; 使用csv.writer插入; between two strings is gross overkill. 两个字符串之间是严重的过度杀伤力。 With that removed, your code works. 删除该代码后,您的代码即可工作。 Also, for purpose of development and posting, use an iterable of lines instead of an external file as source, and print instead of write for output. 另外,出于开发和发布的目的,请使用可迭代的行而不是外部文件作为源,并使用print而不是write来进行输出。

import itertools

f1 = '''\
1     abc
1     def
2     ghi
3     jkl
3     mno
3     pqr
'''.splitlines()

for l in itertools.groupby((l.split() for l in f1), lambda x: x[0]):
    grouped = set(x[1] for x in l[1])  # set avoids duplicate rows
    for c in itertools.combinations(grouped, 2):
        print('%s;%s' % c)

prints 版画

abc;def
pqr;mno
pqr;jkl
mno;jkl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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