在我做了一点工作之后,我认为您无法绕过嵌套循环或多次迭代。如果你必须考虑到领带,你将需要迭代内部字典,最坏的情况是你必须迭代所有这些项目来打破平局-所以复杂性保持不变。在data = {1: [{'date': datetime.datetime.strptime('6/30/2015', '%m/%d/%Y'), 'bits': 1},
{'date': datetime.datetime.strptime('6/25/2015', '%m/%d/%Y'), 'bits': 5}],
2: [{'date': datetime.datetime.strptime('7/31/2013', '%m/%d/%Y'), 'bits': 5},
{'date': datetime.datetime.strptime('7/28/2015', '%m/%d/%Y'), 'bits': 3}],
6: [{'date': datetime.datetime.strptime('4/23/2010', '%m/%d/%Y'), 'bits': 10},
{'date': datetime.datetime.strptime('1/2/2009', '%m/%d/%Y'), 'bits': 1}],
7: [{'date': datetime.datetime.strptime('4/24/2010', '%m/%d/%Y'), 'bits': 2},
{'date': datetime.datetime.strptime('1/1/2009', '%m/%d/%Y'), 'bits': 10}]}
尝试利用内置函数^{}和^{}、^{}、^{}、^{}(标准库的所有部分)。即使时间复杂度相同,它们也可以加快速度。在
我们需要编写一个可以与max一起使用的键函数。在
下面的内容可能是指导性的,但它基于bits键来打破联系。它使用一个键函数,从data的每一项的每个内部字典返回已排序的bits值。一定要看到底部的编辑。在
我还使用了一个方便的函数,可以将多个函数串在一起。我的工具箱里有这个,它没有归属,所以我不知道是我写的还是在什么地方找到的-我可能找到了。在
^{pr2}$
我们需要data中每个(k,v)项的值。在#callable that returns sequence[1]
item1 = operator.itemgetter(1)
我们需要一些东西来获得内部字典的bits值#callable that returns subscriptable['bits']
bits = operator.itemgetter('bits')
我们需要遍历每个内部字典并提取bits#callable that will map the callable bits to a sequence
#this becomes an inner nested loop
get_bits = functools.partial(map, bits)
我们需要反向排序reverse_sort = functools.partial(sorted, reverse = True)
编写一个键函数,返回您感兴趣的内容。在funcs = [reverse_sort, get_bits, item1]
key = compose(funcs)
# key is now equivalent to sorted(get_bits(item1(item)), reverse = True)
>>> # iterate over data.items() and find the max
>>> print(max(data.items(), key = key))
(7, [{'date': '4/23/2010', 'bits': 2}, {'date': '1/1/2009', 'bits': 10}])
不知道我为什么喜欢函数式的风格,但是你也可以像这样写关键函数(我想,很多人会发现这种方法更具可读性)。在def key1(item):
one = item[1]
# iterate over the inner dictionaries
bits = [thing['bits'] for thing in one]
# sort the bits
return sorted(bits, reverse = True)
>>> print(max(data.items(), key = key1))
(7, [{'date': '4/23/2010', 'bits': 2}, {'date': '1/1/2009', 'bits': 10}])
编辑
似乎我读错了或者没有看到tiebreaker是date字段。
这样就容易多了。在#callable that returns a ('bits', 'date') tuple
bits_date = operator.itemgetter('bits', 'date')
def key3(item):
'''return the best dictionary from an item
'''
one = item[1]
# max is an inner loop when this is used as a key function
return max(one, key = bits_date)
# or
item1 = operator.itemgetter(1)
best = functools.partial(max, key = bits_date)
key4 = compose([best, item1])
>>> # max in the next statement(s) is the outer loop
>>> print(max(d.items(), key = key3))
(6, [{'date': datetime.datetime(2010, 4, 23, 0, 0), 'bits': 10}, {'date': datetime.datetime(2009, 1, 2, 0, 0), 'bits': 1}])
>>> print(max(d.items(), key = key4))
(6, [{'date': datetime.datetime(2010, 4, 23, 0, 0), 'bits': 10}, {'date': datetime.datetime(2009, 1, 2, 0, 0), 'bits': 1}])
>>>