ソートされたデータセットをループし、そのソートされた属性によってすべての結果をその属性に対して同じ値を持つチャンクにグループ化する必要があります。次に、その結果のチャンクに対していくつかの操作を実行します。
少し混乱させて申し訳ありませんが、例はおそらく私がやっていることを説明するためのより良い方法です:
「データ」文字列が実際にはオブジェクトであり、他の多くのデータが含まれていることを除いて、このように構造化されたデータセットがあります。
[ [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 への 2 回目の呼び出しですべてを追跡する必要があります。誰かがよりエレガントで賢い解決策を提案できるかどうか知りたいです。
私が選んだ言語は Python ですが、一般的な解決策で問題ありません。