简体   繁体   English

给定一个字符串列表,每个字符串由逗号分隔的子字符串组成,如何重新排序子字符串?

[英]Given a list of strings, each consisting of substrings separated by commas, how can I reorder the substrings?

I have a list of names in an excel file that I have copied into a text file.我有一个 excel 文件中的名称列表,我已将其复制到文本文件中。 The format of the names is "last name, pre-names" where pre-names are first names (and middle names when applicable).姓名的格式是“姓氏,前名”,其中前名是名字(适用时还有中间名)。 In a handful of cases, there are two middle-names.在少数情况下,有两个中间名。 How can I remove the comma and change the order of the names so that the first names (and middle names) come before the last name?如何删除逗号并更改名称的顺序,以便名字(和中间名)在姓氏之前?

Original:原来的:

lastname1, firstname1
lastname2, firstname2 middlename2
lastname3, firstname3

What I want:我想要的是:

firstname1 lastname1
firstname2 middlename2 lastname2
firstname3 lastname3

PS - I teach labs at my local university and this is for a gradebook consisting of hundreds of names. PS -我在当地大学教实验室,这是一个由数百个名字组成的成绩簿。

You can use split, to divide the names on the comma:您可以使用 split, 将逗号上的名称分开:

for name in names:
    last, first = name.split(',', 1)
    print(first, last)

Sample data:样本数据:

names = [x.strip() for x in """
    lastname1, firstname1
    lastname2, firstname2 middlename2
    lastname3, firstname3
""".split('\n')[1:-1]]

Prints:印刷:

firstname1 lastname1
firstname2 middlename2 lastname2
firstname3 lastname3

If you need to read names from a file:如果您需要从文件中读取名称:

with open("file_location/file_name.txt") as f:
    names = f.readlines() 

It depends on what environment (or application) you are using.这取决于您使用的环境(或应用程序)。 For excel, I would simply import the text data and tell excel that it is comma delimited text.对于 excel,我会简单地导入文本数据并告诉 excel 它是逗号分隔的文本。 Here is how to do it (Microsoft link) Text Import Wizard这是如何做到的(Microsoft 链接) 文本导入向导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM