0

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?

0

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

How can you say it works when you have a different output ?
@Gribouillis Textnet effectively declared the order within pairs to not be relevant by using sets as the input to combinations(). Ditto for the order of pairs from each group. To make the output deterministicly ordered, one would have to use the set to create an no-dups sequence from l, and then feed the sequence to combinations().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.