优化方法(由复合字典键(<skill name>,<column name>)
和dict.get
方法提供支持)
header = ['names']
names = set()
d = {}
for lst in in_data:
col_name = lst[0][-1]
header.append(col_name)
for name,val in lst[1:]:
names.add(name)
d[name,col_name] = val
res = [[n,*[d.get((n,h),'-') for h in header[1:]]] for n in names]
res.insert(0,header)
print(res)
输出:
[['names','name_1','name_2','name_3'],['item_C','3','-','7'],['item_D','4','-'],['item_B','2','5','6'],['item_A','-']]
,
您可以使用collections.defaultdict
:
import collections
in_data = [[['name','name_1'],'2'],'3'],'4']],[['Skill','name_2'],'5'],'2']],'7']]]
d = [list(zip(['name',*b[0][1:]],i)) for b in in_data for i in b[1:]]
new_d = collections.defaultdict(dict)
for i in d:
new_d[dict(i)['name']][i[-1][0]] = i[-1][-1]
all_names = list({i for b in new_d.values() for i in b})[::-1]
result = [['name',*all_names],*[[a,*[b.get(k,'-') for k in all_names]] for a,b in new_d.items()]]
输出:
[['name','-']]
本文链接:https://www.f2er.com/3128577.html