将姓氏、名字切换到列表中的名字姓氏 [英] Switch Lastname, Firstname to Firstname Lastname inside List

查看:58
本文介绍了将姓氏、名字切换到列表中的名字姓氏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个运动员名单.一种结构简单:

I have two lists of sports players. One is structured simply:

['Lastname, Firstname', 'Lastname2, Firstname2'..]

第二个是结构化列表:

[['Firstname Lastname', 'Team', 'Position', 'Ranking']...]

我最终想搜索第二个列表的内容,如果第一个列表中有匹配的名称,则提取信息.

I ultimately want to search the contents of the second list and pull the info if there is a matching name from the first list.

我需要将 'Lastname, Firstname' 交换为 'Firstname Lastname' 以匹配列表 2 的格式以进行简化.

I need to swap 'Lastname, Firstname' to 'Firstname Lastname' to match list 2's formatting for simplification.

任何帮助都会很棒.谢谢!

Any help would be great. Thanks!

推荐答案

您可以用以下方式交换名称列表中的顺序:

You can swap the order in the list of names with:

[" ".join(n.split(", ")[::-1]) for n in namelist]

<小时>

解释:这是一个列表推导式,对每个项目做一些事情.以下是一些中间版本以及它们将返回的内容:


An explanation: this is a list comprehension that does something to each item. Here are a few intermediate versions and what they would return:

namelist = ["Robinson, David", "Roberts, Tim"]
# split each item into a list, around the commas:
[n.split(", ") for n in namelist]
# [['Robinson', 'David'], ['Roberts', 'Tim']]

# reverse the split up list:
[n.split(", ")[::-1] for n in namelist]
# [['David', 'Robinson'], ['Tim', 'Roberts']]

# join it back together with a space:
[" ".join(n.split(", ")[::-1]) for n in namelist]
# ['David Robinson', 'Tim Roberts']

这篇关于将姓氏、名字切换到列表中的名字姓氏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆