1

I'm trying to do something like that:

groups = groupby(all_data, key=itemgetter(1))
result = []
for k,g in groups:
    gg = list(g)
    count = len(gg)
    v = gg[0][3:] #No empty groups, right?
    hosts = ";".join([x[0] for x in gg])
    result.append(v + (count,) + (hosts,))

I hate loops. ;) Is there any chance to do it with comprehension? The problem is g is iterator, not list and I have no idea how can I convert it to list in comprehension.

2
  • Maybe you look for something like that [list(g)[0][3:] + (len(list(g)),) + (';'.join(x[0] for x in list(g)[0][3:])) for k, g in itertools.groupby(all_data, itemgetter(1))] however it would be better if you provide your input and your expected output. Commented May 4, 2018 at 10:20
  • 1
    This is way too much code to put into a list comprehension. Why would you ever try to convert 8(!) lines of code into a single one? If you want a better way to write this loop, ask for a better way to write this loop. Don't ask for a list comprehension, because that's a worse way to write this loop. Commented May 4, 2018 at 10:21

1 Answer 1

3

There is no need or significant benefit in converting this into a list comprehension. You may be left with unreadable code that only you can understand.

One stylistic point I do support is not to create lists prematurely or unnecessarily. This leaves the option open to iterate results rather than build a list containing all the results.

For example:

from itertools import groupby
from operator import itemgetter

all_data = [('A', 'B', 'C', 'S', 'T'),
            ('E', 'B', 'C', 'U', 'V'),
            ('H', 'I', 'J', 'W', 'X')]

groups = groupby(all_data, key=itemgetter(1))

def fun(groups):
    for _, g in groups:
        gg = list(g)
        hosts = ';'.join(list(map(itemgetter(0), gg)))
        yield gg[0][3:] + (len(gg),) + (hosts,)

res = list(fun(groups))

[('S', 'T', 2, 'A;E'),
 ('W', 'X', 1, 'H')]
Sign up to request clarification or add additional context in comments.

Comments

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.