问题
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