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

本文介绍了Python中operator模块的使用方法,特别是itemgetter函数如何应用于列表和字典的排序。通过实例展示了如何定义排序规则并按点击数对数据进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python的排序参见文章http://blog.youkuaiyun.com/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'] + '\n'
                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'>

这说明

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值