zoukankan      html  css  js  c++  java
  • 字典---Python

    创建字典,增添内容{‘键’:‘值’}:

    world={'tow':'tree','three':'pig'}---初始内容
    world['one']='flower'---增添内容

    world=dict()---初始为空
    {}

    查找字典中的值:

    vals=world.values()----列表形式返回字典中的内容

    'flower'in vals----查找,返回布尔类型

    使用字典计数:

    def count(s):
        d=dict()
        for i in s:
            if i not in d:
                d[i]=1
            else:
                d[i]+=1

        return d
    s='sdfjsksssdf'
    diction=count(s)
    print(diction)

    diction.get('a',0)---接收键值和默认值,如该键出现在字典中返回相应值,否则返回默认值

    遍历字典:

    world={'tow':'tree','three':'pig'}
    world['one']='flower'
    for c in world:
        print(c,world[c])

    字典反转:

    def invert_dict(d):
        invert=dict()
        for key in d:
            val=d[key]
            if val not in invert:
                invert[val]=[key]
            else:
                invert[val].append(key)
        return invert

    def hist(h):
        d=dict()
        for c in h:
            if c not in d:
                d[c]=1
            else:
                d[c]+=1
        return d
    h=hist('parrot')
    invert=invert_dict(h)
    print(h)
    print(invert)

    结果:

    {'t': 1, 'o': 1, 'a': 1, 'p': 1, 'r': 2}
    {1: ['t', 'o', 'a', 'p'], 2: ['r']}

    全局变量:

    been_called = False---全局变量
    def example():
        global been_called---生命全局变量(如不声明,则视为新建的局部变量)
        been_called=True----修改全局变量

    注:如果全局变量是可变的(列表、字典),则不用声明即可进行修改,如想要重新赋值则需要声明

  • 相关阅读:
    ubuntu install gobgp
    ubunut install golang
    Using GoBGP as an IXP connecting router
    400 行 C 代码实现一个虚拟机
    IPv6 Segment Routing (SRv6)
    How to Install VPP in ubuntu x86 or arm64
    mpls + sr + bgp
    ospf sr
    520了,用32做个简单的小程序
    FPGA设计经验总结
  • 原文地址:https://www.cnblogs.com/lwjl/p/4226606.html
Copyright © 2011-2022 走看看