您的位置:首页 > 编程语言 > Python开发

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

2015-01-14 16:44 676 查看
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)

2

>>> 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'>

这说明
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: