这个是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表示从大到小排序