如何根据自定义键 python 弹出列表的最大值
how to pop max of the list based on customized key python
我有一个字符串列表:["abc", "a", "abcdef", "g", "h"]
。我正在尝试根据自定义键弹出列表的最大值。在这种情况下,我的自定义键是列表中项目的长度:
Input: ["abc", "a", "abcdef", "g", "h"]
Output: "abcdef", 6
其中自定义键是 len
。此外,该列表将没有最大项目:["abc", "a", "g", "h"]
。有什么办法吗?
>>> strings = ["abc", "a", "abcdef", "g", "h"]
>>> strings.remove(max(strings, key=len))
>>> strings
['abc', 'a', 'g', 'h']
>>> def pop_max(iterable, key=lambda x: x):
... m = max(iterable, key=key)
... iterable.remove(m)
... return m, key(m)
...
>>> pop_max(["abc", "a", "abcdef", "g", "h"])
('h', 'h')
>>> pop_max(["abc", "a", "abcdef", "g", "h"], key=len)
('abcdef', 6)
我有一个字符串列表:["abc", "a", "abcdef", "g", "h"]
。我正在尝试根据自定义键弹出列表的最大值。在这种情况下,我的自定义键是列表中项目的长度:
Input: ["abc", "a", "abcdef", "g", "h"]
Output: "abcdef", 6
其中自定义键是 len
。此外,该列表将没有最大项目:["abc", "a", "g", "h"]
。有什么办法吗?
>>> strings = ["abc", "a", "abcdef", "g", "h"]
>>> strings.remove(max(strings, key=len))
>>> strings
['abc', 'a', 'g', 'h']
>>> def pop_max(iterable, key=lambda x: x):
... m = max(iterable, key=key)
... iterable.remove(m)
... return m, key(m)
...
>>> pop_max(["abc", "a", "abcdef", "g", "h"])
('h', 'h')
>>> pop_max(["abc", "a", "abcdef", "g", "h"], key=len)
('abcdef', 6)