循环遍历列表并将字符串保存到字典中

发布于 2025-01-11 07:56:34 字数 513 浏览 0 评论 0原文

我有一个目录中的文件列表,我想通过删除“.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

合久必婚 2025-01-18 07:56:34

如果您坚持分别跟踪“model”和“fore”,请使用 list 来跟踪与给定模型相对应的所有 fore

from collections import defaultdict


model_files = defaultdict(list)


files = ['MIROC_MAXUSEIS.csv', 'MIROC_MINALL.csv', 'MIROC_MINARO.csv', 'BIPOC_HEEBY.csv', 'BIPOC_JEEBY.csv']


for filename in files:
    model, *fore = filename.strip(".csv").split("_")
    model_files[model].extend(fore)

输出:

defaultdict(list, {'MIROC': ['MAXUSEIS', 'MINALL', 'MINARO'], 'BIPOC': ['HEEBY', 'JEEBY']})

If you insist on tracking both "model" and "fore" separately, use a list to track all the fore which correspond to a given model:

from collections import defaultdict


model_files = defaultdict(list)


files = ['MIROC_MAXUSEIS.csv', 'MIROC_MINALL.csv', 'MIROC_MINARO.csv', 'BIPOC_HEEBY.csv', 'BIPOC_JEEBY.csv']


for filename in files:
    model, *fore = filename.strip(".csv").split("_")
    model_files[model].extend(fore)

Output:

defaultdict(list, {'MIROC': ['MAXUSEIS', 'MINALL', 'MINARO'], 'BIPOC': ['HEEBY', 'JEEBY']})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文