find the most frequent pair in the list of dictionary - python

这个是COMP1531的一次作业:
A pickled file with data in it is stored in shapecolour.p. Write a function most_common inside program unpickle.py that un-pickles this file, and analyses the data to returns what the most common shape-colour pair is.
The return value of unpickle.py should be (for example, if the most common dictionary pair is red circle) the dictionary:

{
    "Colour": "red",
    "Shape": "circle"
}

Ensure your code is pylint compliant.

我的直觉快速解法:

import pickle                                                                                                                                                         
def most_common():
	'''
    un-pickle the file, and analyses the data to 
    returns what the most common shape-colour pair is.
    '''
	''' read data'''
    f = open('shapecolour.p', 'rb')
    data = pickle.load(f)
    
    ''' combine it as a new string and store it'''
    new = []
    for item in data:
        new.append(item['colour'] + ' ' + item['shape'])
        
    ''' find the string appeared most'''
    max = 0
    result = {
                'Colour': None,
                'Shape': None,
            }
    for item in new:
        if new.count(item) > max:
            max = new.count(item)
            x =item.split(' ')
            result = {
                        'Colour': x[0],
                        'Shape': x[1],}
	return result

这是有点奇怪的解法:

import pickle                                                                                                                                                         
def most_common():
    '''
    un-pickle the file, and analyses the data to 
    returns what the most common shape-colour pair is.
    '''
    data = pickle.load(open('shapecolour.p','rb'))
    
    # Transfer the data to the strings, count the frequency of the
    # stirngs and show it in dictionary
    new_list = []
    data_string = [str(item) for item in data]
    for item_string in data_string:
        item = eval(item_string)#!!eval(): eg: eval("print('wow')") -> >>> wow
        item.update({'freq':data_string.count(item_string)})
        new_list.append(item)
        
    # Sort the dictionary in terms of the freq keys and pick the
    # most frequent one
    list_sorted = sorted(new_list, key = lambda item: item['freq'],
        reverse = True)
    # [item.pop('freq') for item in list_sorted]
    for item in list_sorted:
        del item['freq']

    return list_sorted[0]

比较新的内容有eval()和sorted()的用法:
eval(): 会将字符串表达的命令执行出来,需要小心使用 - eval(“print(‘wow’)”) -> >>> wow
sorted(): key要跟上排序规则,这里是根据item[‘freq’]的大小排序,reverse = True表示从大到小排序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值