如何更改列表中的名称顺序,以便名字在姓氏之前?这是我的样本列表:
names = ['Snow, John', 'Stark, Ariya', 'Baratheon, Myrcella']
答案 0 :(得分:4)
试试这个
>>> [', '.join(reversed(name.split(', '))) for name in names]
['John, Snow', 'Ariya, Stark', 'Myrcella, Baratheon']
答案 1 :(得分:1)
split
", "
名称,交换名字和姓氏,join
按" "
分隔。你可以在(嵌套)列表理解中完成所有这些:
>>> [" ".join([first, last]) for last, first in (name.split(", ") for name in names)]
['John Snow', 'Ariya Stark', 'Myrcella Baratheon']
或更短,使用reversed
来反转名字和姓氏:
>>> [" ".join(reversed(name.split(", "))) for name in names]
['John Snow', 'Ariya Stark', 'Myrcella Baratheon']