如何在列表中添加另一个项目,如果键已被使用,则它是字典的值



好了,作为前言,这使用了文件输入和输出,我完全不知道我在做什么。基本上,我有一个数据文件姓名,日期,时间姓名,日期,时间姓名,日期,时间等。每个值都是字符串。现在我把它转换成一个像{"name1";; ["time1, date1"], "name2"; ["time2, date2"], "name3"; ["time3, date3"]}这样的字典问题是,如果文件中有一个重复名称,我希望它像这样追加到字典中name1": ["time1, date1", "time4, date4"]但我现在有很多问题。代码的第一部分只是按照我想要的方式获取名字和日期,这可能效率很低,但我也不在乎。这个循环可能没有任何意义,因为我一直在玩它,但我现在只是不知所措。我的格式可能也不是很好,抱歉。我真的不知道我在做什么。

datafile.txt:

James, Blake, 10:22:00, 09/5/2021
Donald, Yun, 10:22:03, 09/5/2021
Rain, Cloud, 10:22:04, 09/5/2021
Thunder, Storm, 10:22:07, 09/5/2021
Blue, Sky, 10:22:09, 09/5/2021
Green, Grass, 10:22:16, 09/5/2021
Starry, Night, 10:22:18, 09/5/2021
James, Blake, 10:22:03, 09/6/2021

代码文件:


a = {}
with open("datafile.txt") as f:
for line in f:
line = line.strip()
line = line.split(", ")
line[0:2] = [", ".join(line[0:2])]
line[1:] = [", ".join(line[1:])]
for i in range(1):
if line[i] in a:
a[line[i]].append(line[1])
else:
a[line[i]] = [line[1]]
print(a)

数据文件的复杂结构使您出了问题。我建议将这4个字段分解为4个命名变量,以使它们更容易保持直接:

a = {}
with open("datafile.txt") as f:
for line in f:
fname, lname, time, date = line.strip().split(", ")
a.setdefault(f"{fname}, {lname}", []).append(f"{time}, {date}")
print(a)
{'James, Blake': ['10:22:00, 09/5/2021', '10:22:03, 09/6/2021'], 'Donald, Yun': ['10:22:03, 09/5/2021'], 'Rain, Cloud': ['10:22:04, 09/5/2021'], 'Thunder, Storm': ['10:22:07, 09/5/2021'], 'Blue, Sky': ['10:22:09, 09/5/2021'], 'Green, Grass': ['10:22:16, 09/5/2021'], 'Starry, Night': ['10:22:18, 09/5/2021']}

如果您有能力更改数据文件的格式,这将使事情变得非常容易—例如,如果您只是使用标准的CSV格式(引用包含分隔符的字段),则文件将看起来像:

"James, Blake","10:22:00, 09/5/2021"
"Donald, Yun","10:22:03, 09/5/2021"
"Rain, Cloud","10:22:04, 09/5/2021"
"Thunder, Storm","10:22:07, 09/5/2021"
"Blue, Sky","10:22:09, 09/5/2021"
"Green, Grass","10:22:16, 09/5/2021"
"Starry, Night","10:22:18, 09/5/2021"
"James, Blake","10:22:03, 09/6/2021"

,然后你的代码就不需要处理解析成四个字段,然后重新组合成两个:

import csv
a = {}
with open("datafile.txt") as f:
for name, time_date in csv.reader(f):
a.setdefault(name, []).append(time_date)

print(a)

相关内容

  • 没有找到相关文章

最新更新