How to reorganize a list of tuples?

[亡魂溺海] 提交于 2019-12-13 09:54:57

问题


Say I had a list of tuples:

[(98, 'studentA'), (97, 'studentB'), (98, 'studentC'), (95,'studentD')]

And I wanted to organize it so that the students are grouped together by the first number in the tuple, what would be the best approach?

I was thinking about creating an array of lists, in which each index of the array would be a different score (98, 97, and 95 in this example) and the students would be in the list at that index. For a much larger dataset I was considering creating a chaining hash table, but I wasn't sure what to % it to, to guarantee that two scores that aren't the same won't get hashed to the same spot.


回答1:


Why not use a dict? collections.defaultdict would work too:

d = defaultdict(list)
for score, student in l:
    d[score] += student



回答2:


Try using sorted with a key of the number

sorted(students, key=(lambda x: x[0]))

But a dictionary would be a better idea for a large dataset



来源:https://stackoverflow.com/questions/45466753/how-to-reorganize-a-list-of-tuples

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!