码迷,mamicode.com
首页 > 编程语言 > 详细

python:字典嵌套列表

时间:2018-04-26 23:23:10      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:def   通过   python字典   数据   对象   默认值   元组   pat   方式   

Python的字典{ }以键值对的形式保存数据,可以以键来访问字典中保存的值而不能用下标访问。字典中几乎可以包含任意的变量,字典,数列,元组。数列也一样。

python的列表[ ]与字典不同,列表通过单个元素来保存内容,通过下标访问元素。

python字典嵌套列表实现的就是{key1:[ ] , key2:[ ] ,...}

其中,append() 方法用于在列表末尾添加新的对象。Python 字典 setdefault() 函数和get()类似, 如果键不存在于字典中,将会添加键并将值设为默认值。Python 字典 in 操作符用于判断键是否存在于字典中,如果键在字典dict里返回true,否则返回false。(python2 还是has.key方法)

最近要实现的一个结果统计则利用了这种方式实现对不同ID的统计。

代码如下:

# 建立字典
for id,file in enumerate(img):

    if file.find(gt)==-1:
        predict=file
        label=img[id+1]
        label_path = os.path.join(root, label)
        predict_path = os.path.join(root, predict)
        id = predict.split(_)[0]
        if patientid in dict:
            dict[id].append(label_path)
            dict[id].append(predict_path)
        else:
            dict.setdefault(patientid,[])
            dict[id].append(label_path)
            dict[id].append(predict_path)

 

后续可以先循环读取dict中的key,再通过 dict[key]再对列表进行循环读取。

 

python:字典嵌套列表

标签:def   通过   python字典   数据   对象   默认值   元组   pat   方式   

原文地址:https://www.cnblogs.com/a-little-v/p/8954957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!