更改列表中元素的顺序

时间:2015-05-19 12:20:27

标签: python list python-3.x

如何更改列表中的名称顺序,以便名字在姓氏之前?这是我的样本列表:

names = ['Snow, John', 'Stark, Ariya', 'Baratheon, Myrcella']

2 个答案:

答案 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']