首页 > 解决方案 > 使用循环和 if 条件从另一个 2d 列表制作 2d 列表

问题描述

你好,我在 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])

并通过某种方式正确填充 MathPerStudents。我可以看到 data[i] 无法与 j[i] 进行比较,因为一个是列表,另一个是来自元素的 int。重点在于 for 循环我如何使用 (i) 作为数据列表等列表中的索引。

标签: python

解决方案


使用setdefault

前任:

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]]
result = {}
for k, sub, _ in data:
    result.setdefault(k, []).append(sub)    #Set first element as key and append subject as value
print([[k] + v for k, v in result.items()])   #Form required list

输出:

[['Bob', 'Algebra', 'History', 'Physics', 'Astronomy'],
 ['Allen', 'Algebra', 'History', 'Physics'],
 ['Mary', 'Algebra', 'History', 'Physics', 'Astronomy']]

推荐阅读