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/