这是我的第一篇帖子,所以如果我错过了什么,请告诉我。
我正在做一个CS50初学者python课程,我被一个问题困住了。
长话短说,问题是打开一个csv文件,它看起来如下:
名字,房子
“阿伯特,汉娜”,赫芬帕夫
“钟,凯蒂”,格兰芬多…
所以我很想把它放进字典里(我确实这么做了),但现在的问题是,我应该把“键”的名字分成2。
这是我的代码,但不起作用:
前= []
……
with open(sys.argv[1]) as file:
reader = csv.reader(file)
for name, house in reader:
before.append({"name": name, "house": house})
# here i would love to split the key "name" in "last", "first"
for row in before[1:]:
last, first = name.split(", ")有什么建议吗?
提前谢谢你。
发布于 2022-08-09 08:21:33
在您拥有了具有完整名称的字典之后,您可以将该名称拆分如下:
before = [{"name": "Abbott, Hannah", "house": "Hufflepuff"}]
# Before split
print(before)
for item in before:
# Go through each item in before dict and split the name
last, first = item["name"].split(', ')
# Add new keys for last and first name
item["last"] = last
item["first"] = first
# Remove the full name entry
item.pop("name")
# After split
print(before)您还可以从第一次传递中进行拆分,例如直接存储最后和第一个而不是全名。
https://stackoverflow.com/questions/73288414
复制相似问题