python的operator.itemgetter('click')用于定义获取'click'项的函数

python的排序参见文章http://blog.csdn.net/longshenlmj/article/details/12747195


这里介绍 import operator模块

operator的itemgetter函数用于获取传入参数中某个域的值,如

a = [1,2,3] 
>>> b=operator.itemgetter(1)      //定义函数b,获取对象的第1个域的值
>>> b(a) 

>>> b=operator.itemgetter(1,0)  //定义函数b,获取对象的第1个域和第0个的值
>>> b(a) 
(2, 1)

operator.itemgetter是定义了一个函数,然后利用该函数作用到指定对象上,来获取对应域的值。


b = operator.itemgetter(1)  :定义函数b,用于获取传入的list第1域的值

可以将b用于sort函数的key。作为排序的依据。


adn_app_data_map是个字典


 for key, app_arr in adn_app_data_map.items():

            app_arr.sort(key=operator.itemgetter('click'), reverse=True)
            app_arr = app_arr[:3]
            keys = key.split('#')
            category = keys[0]
            ad_network_id = keys[1]
            ad_id = keys[2]
            for app in app_arr:
                dimension_values = category + '#' + app['app_id'] + '#' + ad_network_id + '#' + ad_id
                record = app['campaign_id'] + ',' + adn_ad_category_app_report + ',' + dimension_values + ',' + app['impression'] +
                         ',' + str(app['click']) + ',' + app['impression_cost'] + ',' + app['click_cost'] + ' '
                csv.writelines(record)




测试如下:

>>> import types
>>> test={'a':'1','b':'2','c':'3','d':'4'}
>>> print test.items()
[('a', '1'), ('c', '3'), ('b', '2'), ('d', '4')]
>>> for key,val in test.items():
    print type(val); 
<type 'str'>
<type 'str'>
<type 'str'>
<type 'str'>

这说明

原文地址:https://www.cnblogs.com/cl1024cl/p/6205393.html