python - group_by 返回重复的键

标签 python python-3.x

Python 3.6 我有一个简单的对象列表:

for obj in obj_ts:
    print(obj['address'])

这告诉我:

mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR
mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR
mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR
mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR
mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR
mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR
mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR
mhRhCZBUP1BsrL6xuXSeAeCNnXcoBHWKAB
mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR
mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR
mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR
mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR

然后我想按这些对象进行分组:

for address, t_list in itertools.groupby(obj_ts, key=lambda obj: obj['address']):
    print(address)

但是我得到了 3 个组,而不是 2 个。

mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR
mhRhCZBUP1BsrL6xuXSeAeCNnXcoBHWKAB
mwpJCSEEkphA1utQGA2Y9Vx8cufv85CgpR

最佳答案

评论中的解决方案:

As mentioned in the 1st paragraph of the groupby docs, you need to sort the data (with the same key function) before passing it to groupby

https://docs.python.org/3/library/itertools.html#itertools.groupby

关于python - group_by 返回重复的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059364/

相关文章:

Python - 如何用另一个列表中的字符串值替换存储在列表中的字符串值?

python - HtmlWindow 无法正确显示图像

python - 如果用户尝试了一个选项,但选项不正确,则返回到某个点并重试 - Python

python - 计算二维数据点数组的最高密度区间 (HDI)

python - 如何检查函数来自哪个模块?

Python - 如何按字符匹配列表元素

python 多线程使用 fcntl flcok 处理文件

python - 打印到 Python : redirect vs print's file argument vs write 中的文件

python - 无法使用 Pyads 建立路线(Python 和 TwinCAT 3)

python - Tkinter 小部件全部打包在同一个框架中