-3

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
sjy
  • 37
  • 1
  • 5
  • Possible duplicate of [Sort a list of tuples by 2nd item (integer value)](https://stackoverflow.com/questions/10695139/sort-a-list-of-tuples-by-2nd-item-integer-value) – Ami Hollander Aug 02 '17 at 16:57
  • Probably the simplest way would just be to fold the list into a dictionary, where the key is the score. The indexing idea would work, but then you have a unnecessarily huge array where most of the elements are `None`. – Carcigenicate Aug 02 '17 at 16:57

2 Answers2

6

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

d = defaultdict(list)
for score, student in l:
    d[score] += student
thaavik
  • 3,257
  • 2
  • 18
  • 25
0

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

Simon Hobbs
  • 990
  • 7
  • 11