In what situation should the built-in 'operator' module be used in python?

前端 未结 6 2172
暖寄归人
暖寄归人 2020-12-23 19:44

I\'m speaking of this module: http://docs.python.org/library/operator.html

From the article:

The operator module exports a set of functions

6条回答
  •  别那么骄傲
    2020-12-23 19:59

    for example get column in list whose member is tuple, sort sequence by column:

    def item_ope():
        s = ['h', 'e', 'l', 'l', 'o']
        print operator.getitem(s, 1)
        # e
        print operator.itemgetter(1, 4)(s)
        # ('e', 'o')
    
        inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
        get_count = operator.itemgetter(1)
        print map(get_count, inventory)
        # [3, 2, 5, 1]
    
        print sorted(inventory, key=get_count)
        # [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
    

    see a more practical example, we want to sort a dict by key or value:

    def dict_sort_by_value():
        dic_num = {'first': 11, 'second': 2, 'third': 33, 'Fourth': 4}
    
        # print all the keys
        print dic_num.keys()
        # ['second', 'Fourth', 'third', 'first']
    
        # sorted by value
        sorted_val = sorted(dic_num.items(), key=operator.itemgetter(1))
        # [('second', 2), ('Fourth', 4), ('first', 11), ('third', 33)]
        print sorted_val
    
        # sorted by key
        sorted_key = sorted(dic_num.items(), key=operator.itemgetter(0))
        print sorted_key
        # [('Fourth', 4), ('first', 11), ('second', 2), ('third', 33)]
    

    another example when we want get the max value and it's index in list:

    def get_max_val_idx():
        lst = [1, 7, 3, 5, 6]
        max_val = max(lst)
        print max_val
        # 7
        max_idx = lst.index(max_val)
        print max_idx
        # 1
    
        # simplify it by use operator
        index, value = max(enumerate(lst), key=operator.itemgetter(1))
        print index, value
        # 1 7
    

    More demos like below:

    import operator
    
    def cmp_fun():
        a, b = 5, 3
        print operator.le(a, b)
        # False
        print operator.gt(a, b)
        # True
    
    
    def lst_ope():
        lst = [1, 2, 3]
        print operator.indexOf(lst, 2)
        # 1
        lst1 = [1, 2, 3, 2]
        print operator.countOf(lst1, 2)
        # 2
    
    
    def cal_ope():
        lst1 = [0, 1, 2, 3]
        lst2 = [10, 20, 30, 40]
        print map(operator.mul, lst1, lst2)
        # [0, 20, 60, 120]
    
        print sum(map(operator.mul, lst1, lst2))
        # 200
    
        a, b = 1, 3
        print operator.iadd(a, b)
        # 4
    

    see more from python doc

提交回复
热议问题