python - 使用循环和 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) 作为数据列表等列表中的索引。
解决方案
使用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']]
推荐阅读
- javascript - 如何使用 CSS 的 before 属性将箭头添加到 MI Popover?
- node.js - 使用节点和 chai/sinon 模拟构造函数
- machine-learning - 用于多类 Logistic 回归的 Octave 中向量(数据集)的向量化标签检测
- sql - Excel VB/SQL 服务器:
- javascript - DataTables js 没有正确排序字符串
- javascript - 更新 componentDidUpdate 上的反应状态时超出最大更新深度
- r - 错误:名称标准化后重复的美学:忽略未知参数:fun.y
- rxjs - 对何时使用 observable 感到困惑
- mongodb - Mongo Java Driver Iterator 身份验证问题
- javascript - 当用户使用 react-dates 输入过去的日期时,onDateChange 返回 null