简体   繁体   中英

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

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

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