• python标准库


    setdefault和defaultdict

    #setdefault
    periodic_table = {'Hydrogen': 1, 'Helium': 2}
    carbon = periodic_table.setdefault('Carbon', 12)
    print(carbon)
    print(periodic_table)
    helium = periodic_table.setdefault('Helium', 947)
    print(helium)
    print(periodic_table)
    
    #defaultdict
    print(int())
    from collections import defaultdict
    periodic_table2 = defaultdict(int)
    periodic_table2['Hydrogen'] = 1
    print(periodic_table2['Lead'])
    print(periodic_table2)
    def no_idea():
        return 'Hub?'
    bestiary = defaultdict(no_idea)
    bestiary['A'] = 'Abominable Snowman'
    print(bestiary['B'])

    输出

    12
    {'Carbon': 12, 'Helium': 2, 'Hydrogen': 1}
    2
    {'Carbon': 12, 'Helium': 2, 'Hydrogen': 1}
    0
    0
    defaultdict(<class 'int'>, {'Lead': 0, 'Hydrogen': 1})
    Hub?

    pprint 

    itertools

    import itertools
    
    count = 0
    for item in itertools.chain([1, 2, 3], ['a', 'b']):
        count += 1
        print('count', count)
        print(item)
    
    print('-------------')
    count = 0
    for item in itertools.cycle([1, 2]):
        count += 1
        print('count', count)
        if count < 5:
            print(item)
        else:
            break
    
    print('-------------')
    #累积的值,默认累积和
    for item in itertools.accumulate([1, 2, 3, 4]):
        print(item)
    
    print('-------------')
    def multiply(a, b):
        return a * b
    
    for item in itertools.accumulate([1, 2, 3, 4], multiply):
        print(item)

    输出

    count 1
    1
    count 2
    2
    count 3
    3
    count 4
    a
    count 5
    b
    -------------
    count 1
    1
    count 2
    2
    count 3
    1
    count 4
    2
    count 5
    -------------
    1
    3
    6
    10
    -------------
    1
    2
    6
    24

    deque 

    #deque是一种双端队列,同时具有栈和队列的特征
    def palindrome(word):
        from collections import deque
        dq = deque(word)
        while len(dq) > 1:
            if dq.popleft() != dq.pop():
                return False
        return True
    
    palindrome('racecar')

     OrderedDict

    Counter计数

  • 相关阅读:
    day02 基本数据类型与运算符
    java的基本数据类型--四类八种
    mysql 语句
    5 函数
    4 流程控制
    2 字符串操作 日期
    在Win7虚拟机下搭建Hadoop2.6.0+Spark1.4.0单机环境
    如何排查java.lang.NoSuchMethodError错误
    搭建Hadoop2.6.0+Eclipse开发调试环境
    在Win7虚拟机下搭建Hadoop2.6.0伪分布式环境
  • 原文地址:https://www.cnblogs.com/jzm17173/p/5739800.html
Copyright © 2020-2023  润新知