我有一个看起来像这样的数组:
array1 = [[4000,"Mark",5],[4100,"George",3],[4000,"Mark",2],[4200,"Steve",4],[4100,"George",2],[4000,"Mark",1]]
我想知道如何重新格式化这个数组看起来像这样:
array2 = [[4000,"Mark",[5,2,1]],[4100,"George",[3,2]],[4200,"Steve",4]]
答案 0 :(得分:6)
您可以使用有序字典(collections.OrderedDict
)将前2个项目作为键存储,将常用数字作为值存储在列表中:
>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> for i,j,k in array1:
... d.setdefault((i,j),[]).append(k)
...
>>> [[i,j,k] for (i,j),k in d.items()]
[[4000, 'Mark', [5, 2, 1]], [4100, 'George', [3, 2]], [4200, 'Steve', [4]]]
答案 1 :(得分:2)
[a+[[c[-1] for c in b]] for a,b in itertools.groupby(operator.itemgetter(0,1),sorted(array1))]
我猜...我怀疑这会帮助你学习任何事情......如果你甚至不知道从哪里开始,在课堂上寻求帮助的更合适的地方(问你的老师或同学)...