您好,我是python新手,我的想法像c#一样,我不能做一些事情。 我有这个清单给我的前任
data = [["Bob","Algebra",5],["Bob","History",4],["Bob","Physics",7],["Bob","Astronomy",5],["Allen","Algebra",5],["Allen","History",4],["Allen","Physics",7],["Mary","Algebra",5],["Mary","History",3],["Mary","Physics",7],["Mary","Astronomy",8]
]
我是如何从中输出的:
MathsPerStudent = [["Bob","Algebra","History","Physics","Astronomy"]
["Allen","Algebra","History","Physics"]
["Mary","Algebra","History","Physics","Astronomy"]]
依我看,我不可能
MathsPerStudents=[[]]
for i in data:
for j in MathsPerStudents:
if data[i][0] == j[0]
MathsPerStudents.append(j[0][i])
并用某种方法来正确填写数学学生。正如我所见,数据[i]无法与j[i]进行比较,因为一个是list,另一个是int from元素。问题是我如何在类似数据列表的列表中使用(i)作为索引
如果列表按名称排序,则可以使用
itertools.groupby
:您可以这样做(不是一行,但可能更容易理解):
这将为您提供一本字典:
如果您愿意,您可以将其转换为列表形式,但对于您试图实现的目标,词典可能更易于使用:
最后的清单如下:
使用
setdefault
Ex:
输出:
相关问题 更多 >
编程相关推荐