[英]How to arrange a list of tuples so that the tuple associated with the highest value compared to other tuple is removed and returns the maximum one
val = [(200, []), (300, [500, 200]), (400, [100, 200, 300]), (400, [])]
largest_val_arrangement(val)
[(200, []), (300, [500, 200]), (400, [100, 200, 300])]
so now (400, [])
is poped out because (400, [100, 200, 300])
has more elements than it. 所以现在
(400, [])
被推出,因为(400, [100, 200, 300])
具有比它更多的元素。
you could use sort
according to the length of the list, and use a dictionary so the last written key "wins". 您可以根据列表的长度使用
sort
,并使用字典,以便最后写入的密钥“获胜”。
Then convert back to tuple
or list
or ... leave as dict
: 然后转换回
tuple
或list
或...作为dict
离开:
val = [(200, []), (300, [500, 200]), (400, [100, 200, 300]), (400, [])]
def largest_val_arrangement(val):
return tuple({k:v for k,v in sorted(val, key = lambda t : len(t[1]))}.items())
largest_val_arrangement(val)
result: 结果:
((200, []), (400, [100, 200, 300]), (300, [500, 200]))
This method, like the sort
it uses, has O(log(n)*n)
complexity, ( dict
has O(1)
average complexity). 该方法与它使用的
sort
类似,具有O(log(n)*n)
复杂度,( dict
具有O(1)
平均复杂度)。
But one-liners aren't always the most efficient solutions. 但是单行并不总是最有效的解决方案。 Here using
sort
is unnecessary, when a good old loop with a marker dict works in O(n)
: 这里使用
sort
是不必要的,当一个带有标记dict的旧循环在O(n)
:
def largest_val_arrangement(val):
d = dict()
for k,v in val:
if k not in d or len(d[k]) < len(v):
d[k] = v
return tuple(d.items())
O(n) solution O(n)解决方案
>>> val = val = [(200, []), (300, [500, 200]), (400, [100, 200, 300]), (400, [])]
>>>
>>> seen = {}
>>> for k, lst in val:
...: if len(lst) > len(seen.get(k, [])):
...: seen[k] = lst
...:
>>> list(seen.items())
[(200, []), (300, [500, 200]), (400, [100, 200, 300])]
Other option, using a default dictionary from collections: 其他选项,使用集合中的默认字典:
val = [(200, []), (300, [500, 200]), (400, [100, 200, 300]), (400, [])]
from collections import defaultdict
tmp = defaultdict(list)
for x in val:
if len(x[1]) > len(tmp[x[0]]): tmp[x[0]] = x[1]
res = [(k, v) for k,v in tmp.items()]
print(res)
#=> [(200, []), (300, [500, 200]), (400, [100, 200, 300])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.