简体   繁体   中英

Python itertools groupby multiple use in list comprehension

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.

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')]

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