循环遍历列表并将字符串保存到字典中
我有一个目录中的文件列表,我想通过删除“.csv”来修改该列表,然后用下划线分隔字符串,然后将其作为键值对添加到字典中。当我像这样设置循环时我只得到列表中的最后一个键/值,所以它似乎覆盖了列表中的我的数据,我想做什么
filedict = dict()
model = []
fore = []
for f in files:
nf = f.replace('.csv','')
model = (nf.split("_")[0])
fore = (nf.split("_")[1])
filedict[model] = fore
files =
['MIROC_MAXUSEIS.csv',
'MIROC_MINALL.csv',
'MIROC_MINARO.csv',]
?
filedict.keys("MIROC", "MIROC", "MIROC") and filedict.values("MAXUSEIS","MINALL","MINARO")
I have a list of files from a directory that I'd like to modify by removing the ".csv. and seperate the string by the underscore then and add to a dictionary as a key-value pair. When I set the loop up like this I only get the last key/value in the list, so it seems to be overwriting my data in the list. What am I doing wrong?
filedict = dict()
model = []
fore = []
for f in files:
nf = f.replace('.csv','')
model = (nf.split("_")[0])
fore = (nf.split("_")[1])
filedict[model] = fore
files =
['MIROC_MAXUSEIS.csv',
'MIROC_MINALL.csv',
'MIROC_MINARO.csv',]
I want
filedict.keys("MIROC", "MIROC", "MIROC") and filedict.values("MAXUSEIS","MINALL","MINARO")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您坚持分别跟踪“model”和“fore”,请使用
list
来跟踪与给定模型相对应的所有fore
:输出:
If you insist on tracking both "model" and "fore" separately, use a
list
to track all thefore
which correspond to a given model:Output: