首页 > 解决方案 > 访问列表 Python 中的特定字符串以在不同的列中分隔

问题描述

我想将列表中名称的值分成 3 个不同的列。我有这个代码

with open(argv[1],"r") as csvdata:

reader = csv.DictReader(csvdata, delimiter = ",")

#Iterate to each column
for row in reader:

    name = row['name'].split()
    house = row['house']
    birth = row['birth']

当我打印值“名称”时,我得到了这个结果:

['Adelaide', 'Murton']
['Adrian', 'Pucey']
['Anthony', 'Goldstein']
['Dean', 'Thomas']
['Draco', 'Lucius', 'Malfoy']
['Ernest', 'Macmillan']
['Ginevra', 'Molly', 'Weasley']
['Gregory', 'Goyle']

现在我的主要问题是我不知道如何将这些值拆分为 3 个不同的名字、中间名和姓氏列。

标签: pythonlistcsv

解决方案


This addresses the problem of dealing with strings containing either two words or three words:

def get_names(name):
    names = name.split()
    if len(names) == 2:
        return [names[0], '', names[1]]
    else:
        return names

print(get_names('Adelaide Murton'))
print(get_names('Draco Lucius Malfoy'))

Running the above code generates this output:

['Adelaide', '', 'Murton']
['Draco', 'Lucius', 'Malfoy']

Note, however, that this will NOT work if the data contains names like Johannes Diderik van der Waals :)


推荐阅读