python - 访问列表 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 个不同的名字、中间名和姓氏列。
解决方案
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 :)
推荐阅读
- javascript - 如何删除反应中不需要的元素?
- reactjs - React useReducer hook,如何处理多个不相关类型的动作?
- next.js - 从 getServerSideProps 或 getStaticProps 获取 NextJs 中菜单项的全局位置
- xml - 使用 Linux perl 程序提取包含特定语言日期值的 Office Open XML 单元格
- java - Android:从 addTextChangedListener 更改为 setOnKeyListener 以使用 Backspace
- javascript - 修复 jQuery 可排序插件的高度和宽度
- postgresql - @CreationTimestamp 更改日期格式
- ios - 从 ios 获取 UnitIlluminance 的浮点数
- reactjs - Redux 不断更新
- css - 引导程序通过链接工作,但下载时不工作