如何重组元组列表? [英] How to reorganize a list of tuples?

查看:124
本文介绍了如何重组元组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个元组列表:

[(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?

我正在考虑创建一个列表数组,其中该数组的每个索引将具有不同的分数(在本示例中为98、97和95),而学生将位于该索引的列表中.对于更大的数据集,我正在考虑创建一个链式哈希表,但是我不确定要添加到哪个哈希表,以确保两个不同的分数不会被哈希到同一位置.

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.

推荐答案

为什么不使用dict? collections.defaultdict也可以:

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

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

这篇关于如何重组元组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆