在Python中,可以使用sorted()
函数和operator.itemgetter()
来按照特定列进行排序。然后,使用itertools.groupby()
函数将具有相同主要索引的项目分组在一起。
下面是一个示例代码:
import operator
import itertools
# 示例数据
data = [
{'主要索引': 1, '列1': 'a', '列2': 2},
{'主要索引': 2, '列1': 'b', '列2': 1},
{'主要索引': 1, '列1': 'c', '列2': 3},
{'主要索引': 2, '列1': 'd', '列2': 4},
{'主要索引': 3, '列1': 'e', '列2': 3},
]
# 按照'主要索引'列进行排序
sorted_data = sorted(data, key=operator.itemgetter('主要索引'))
# 按照'主要索引'列分组
grouped_data = itertools.groupby(sorted_data, key=operator.itemgetter('主要索引'))
# 输出分组结果
for key, group in grouped_data:
print(f'主要索引: {key}')
for item in group:
print(item)
print()
运行以上代码,输出结果如下:
主要索引: 1
{'主要索引': 1, '列1': 'a', '列2': 2}
{'主要索引': 1, '列1': 'c', '列2': 3}
主要索引: 2
{'主要索引': 2, '列1': 'b', '列2': 1}
{'主要索引': 2, '列1': 'd', '列2': 4}
主要索引: 3
{'主要索引': 3, '列1': 'e', '列2': 3}
可以看到,按照'主要索引'列进行排序后,具有相同主要索引的项目被分组在一起。