zoukankan      html  css  js  c++  java
  • !!Python字典增删操作技巧简述+Python字典嵌套字典与排序

    http://developer.51cto.com/art/201003/186006.htm

    Python编程语言是一款比较容易学习的计算机通用型语言。对于初学者来说,首先需要掌握的就是其中的一些基础应用。比如今天我们为大家介绍的Python字典的相关操作,就是我们在学习过程中需要熟练掌握的技巧。

    Python字典(Dictionary)是一种映射结构的数据类型,由无序的“键-值对”组成。字典的键必须是不可改变的类型,如:字符串,数字,tuple;值可以为任何Python数据类型。

    1、新建Python字典

    1. >>> dict1={} #建立一个空字典  
    2. >>> type(dict1)  
    3. < type 'dict'> 

    2、增加Python字典元素:两种方法

    1. >>> dict1['a']=1 #第一种  
    2. >>> dict1  
    3. {'a': 1}  
    4. #第二种:setdefault方法  
    5. >>> dict1.setdefault('b',2)  
    6. 2  
    7. >>> dict1  
    8. {'a': 1, 'b': 2} 

    3、删除Python字典

    1. #删除指定键-值对  
    2. >>> dict1  
    3. {'a': 1, 'b': 2}  
    4. >>> del dict1['a'] #也可以用pop方法,dict1.pop('a')  
    5. >>> dict1  
    6. {'b': 2}  
    7. #清空字典  
    8. >>> dict1.clear()  
    9. >>> dict1 #字典变为空了  
    10. {}  
    11. #删除字典对象  
    12. >>> del dict1  
    13. >>> dict1  
    14. Traceback (most recent call last):  
    15. File "< interactive input>", line 1, in < module> 
    16. NameError: name 'dict1' is not defined 

    4)对字典的遍历

    python 代码
    >>> table = {'abc':1, 'def':2, 'ghi':3}  
    >>> for key in table.keys():  
        print key, '/t', table[key]  
     
          
    abc     1  
    ghi     3  
    def     2 

    Python字典嵌套字典与排序 

    http://muilpin.blog.163.com/blog/static/16538293620113112549775/

    背景:计算图形中任意点与点的曼哈顿距离:
    x=[1,2,3,4,5,6,7,8,9,2]
    y=[2,3,2,5,6,7,2,3,5,5]
    n=10
    distance=[[0 for j in range(n)]for i in range(n)]

    定义二层嵌套字典与二维数组:
    result={}
    for i in range(n):
        result[str(i)]={}  #定义嵌套字典
    另外定义二维数组与字典方式不一样:
    n=16
    distance=[[0 for j in range(n)]for i in range(n)]

    给字典赋值:
    for i in range(n):
        for j in range(n):
            distance[i][j]=abs(x[i]-y[j])  #计算曼哈顿距离
            result[str(i)][str(j)]=distance[i][j]

    字典按照值(values)排序:
    result_sort[i]=[(k,v) for (k,v) in result[str(i)].iteritems()]   #将嵌套中第二维字典的转变成列表
    使用列表排序函数sorted()排序:
    result_sort[i]=sorted(result_sort[i],key=lambda x:x[1],reverse=False)

    Python多维/嵌套字典数据无限遍历

    http://www.cnblogs.com/lhj588/archive/2012/05/24/2516046.html

  • 相关阅读:
    深入剖析C#的多态
    .NET多线程编程:多任务和多线程
    .Net类库中实现的HashTable
    用C#编写ActiveX控件
    用微软.NET架构企业解决方案 学习笔记(四)业务层
    SQL事务
    WCF基础知识问与答
    在.NET环境中使用单元测试工具NUnit
    圣殿骑士博客转载系列
    系统架构师学习笔记_第十二章
  • 原文地址:https://www.cnblogs.com/carl2380/p/3208151.html
Copyright © 2011-2022 走看看