[英]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.
问题是g是迭代器,而不是列表,我不知道如何将其转换为列表。
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')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.