zoukankan      html  css  js  c++  java
  • python:字典嵌套列表

    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]再对列表进行循环读取。

  • 相关阅读:
    安装minicom串口访问开发板
    《Linux运维趋势》2010-2013年全部期刊下载
    pap与chap协议
    简单linux网络驱动程序
    573. Squirrel Simulation
    576. Out of Boundary Paths
    568. Maximum Vacation Days
    leetcode contest 20
    55 Jump Game i && 45 Jump Game ii
    120. Triangle
  • 原文地址:https://www.cnblogs.com/a-little-v/p/8954957.html
Copyright © 2011-2022 走看看