data = ['ID:123 GE:m FN:Amir LN:Maleki MN:0400101010 EM:a@b.c ST:VIC',
'ID:b22 EM:b@d.c ST:VIC GE:F FN:Miniyi LN:Li MN:0430101210 MN:0432101215',
'ID:153 GE:m FN:John LN:Liu MN:040181010 ST:NSW EM:d@b.c']
我希望以
的顺序排列以下数据key_order = 'ID', 'GE', 'FN', 'LN', 'MN', 'EM', 'ST'
当使用此代码有一个字符串时,我可以这样做:
data = ['ID:153 GE:m FN:John LN:Liu MN:040181010 ST:NSW EM:d@b.c']
data = data[0].split()
keyorder = ['ID', 'GE','FN','LN','MN','EM', 'ST']
print(sorted(data, key=lambda x: key_order.index(x.split(':')[0])))
['ID:153', 'GE:m', 'FN:John', 'LN:Liu', 'MN:040181010', 'EM:d@b.c', 'ST:NSW']
同时也难以将最终结果显示为:
ID:123 GE:m FN:Amir LN:Maleki MN:0400101010 EM:a@b.c ST:VIC
ID:b22 EM:b@d.c ST:VIC GE:F FN:Miniyi LN:Li MN:0430101210 MN:0432101215
ID:153 GE:m FN:John LN:Liu MN:040181010 ST:NSW EM:d@b.c
谢谢堆
答案 0 :(得分:3)
你非常接近正确答案:
def sort_by_key(x):
return key_order.index(x.split(':')[0])
for d in data:
print(" ".join(sorted(d.split(), key=sort_by_key)))
#ID:123 GE:m FN:Amir LN:Maleki MN:0400101010 EM:a@b.c ST:VIC
#ID:b22 GE:F FN:Miniyi LN:Li MN:0430101210 MN:0432101215 EM:b@d.c ST:VIC
#ID:153 GE:m FN:John LN:Liu MN:040181010 EM:d@b.c ST:NSW