我需要遍历一个已排序的数据集,将所有结果按该排序的属性分组到 block 中,这些 block 都具有相同的属性值。然后我对该 block 结果运行一些操作。
抱歉,这有点令人困惑,示例可能是描述我正在做的事情的更好方式:
我有一个结构如下的数据集,除了“数据”字符串实际上是对象并且包含大量其他数据。
[ [1, "data1"], [1, "data2"], [2, "moredata"], [2, "stuff"],
[2, "things"], [2, "foo"], [3, "bar"], [4, "baz"] ]
我想要的是将数据分组到 4 个不同的函数调用中:
process_data(1, ["data1", "data2"])
process_data(2, ["moredata", "stuff", "things", "foo"])
process_data(3, ["bar"])
process_data(4, ["baz"])
我最终得到的是一个看起来像这样的结构:
last_id = None
grouped_data = []
for row in dataset:
id = row[0]
data = row[1]
if last_id != id:
# we're starting a new group, process the last group
processs_data(last_id, grouped_data)
grouped_data = []
last_id = id
grouped_data.append(data)
if grouped_data:
# we're done the loop and we still have a last group of data to process
# if there was no data in the dataset, grouped_data will still be empty
# so we won't accidentally process any empty data.
process_data(last_id, grouped_data)
它有效,但看起来很笨拙。特别是需要使用 last_id 变量跟踪所有内容以及循环后对 process_data 的第二次调用。我只想知道是否有人可以为更优雅/更聪明的解决方案提供任何建议。
我选择的语言是 Python,但通用的解决方案很好。
最佳答案
itertools.groupby 正是您想要的:
>>> data = [ [1, "data1"], [1, "data2"], [2, "moredata"], [2, "stuff"],
... [2, "things"], [2, "foo"], [3, "bar"], [4, "baz"] ]
>>>
>>> from itertools import groupby
>>> from operator import itemgetter
>>>
>>> def process_data(key, keydata):
... print key, ':', keydata
...
>>> for key,keydata in groupby(data, key=itemgetter(0)):
... process_data(key, [d[1] for d in keydata])
...
1 : ['data1', 'data2']
2 : ['moredata', 'stuff', 'things', 'foo']
3 : ['bar']
4 : ['baz']
向 groupby 传递一个排序列表,以及一个关于列表中每个项目的分组依据的关键函数。你会得到一个 (key,itemgenerator)
对的生成器,如图所示传递到我制作的 process_data 方法。
关于python - 在 for 循环中分组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11823266/