你好,我在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。正如我所看到的,datai不能与ji相比,因为其中一个是list,另一个是int from element。关键在于for循环,如何将(i)用作像数据列表这样的列表中的索引。
发布于 2020-05-20 08:04:40
使用setdefault
Ex:
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']]发布于 2020-05-20 08:13:37
您可以这样做(不是一条直线,但可能更容易理解):
MathsPerStudent = {}
for name, subject, grade in data:
if name not in MathsPerStudent:
MathsPerStudent[name] = []
MathsPerStudent[name].append(subject)这给了你一本字典:
>>> from pprint import pprint
>>> pprint(MathsPerStudent)
{'Allen': ['Algebra', 'History', 'Physics'],
'Bob': ['Algebra', 'History', 'Physics', 'Astronomy'],
'Mary': ['Algebra', 'History', 'Physics', 'Astronomy']}如果您想要的话,可以将其转换为列表形式,但对于任何您想要实现的目标,使用字典可能会更容易:
MathsPerStudentList = [[name] + subjects for name, subjects in MathsPerStudent.items()]以下是最后一份清单:
>>> pprint(MathsPerStudentList)
[['Bob', 'Algebra', 'History', 'Physics', 'Astronomy'],
['Allen', 'Algebra', 'History', 'Physics'],
['Mary', 'Algebra', 'History', 'Physics', 'Astronomy']]发布于 2020-05-20 08:15:15
如果列表是按名称排序的,则可以使用itertools.groupby:
import itertools
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]]
output = []
for student, classes in itertools.groupby(data, key=lambda x: x[0]):
output.append([student] + [entry[1] for entry in classes])
print(output)https://stackoverflow.com/questions/61907997
复制相似问题