通过键从listOfLists组中获取最小的项目

Pat*_*hen 2 python

我有一个像这样的清单

listOfLists = [['key2', 1], ['key1', 2], ['key2', 2], ['key1', 1]]
Run Code Online (Sandbox Code Playgroud)

内部列表的第一项是密钥.内部列表的第二项是值.

我想得到一个输出[['key1', 1], ['key2', 1]],它给出列表,它的值是具有相同键的列表中的最小值,而键是输出组(我的英语很差,所以只使用Sql语法的概念)

我写了一些像这样的代码:

listOfLists = [['key2', 1], ['key1', 2], ['key2', 2], ['key1', 1]]
listOfLists.sort()    #this will sort by key, and then ascending by value
output = []
for index, l in enumerate(listOfLists):
    if index == 0:
        output.append(l)
    if l[0] == listOfLists[index - 1][0]:
        #has the same key, and the value is larger, discard
        continue
    else:
        output.append(l)
Run Code Online (Sandbox Code Playgroud)

这似乎不够聪明是否有更简单的方法来完成这项工作?

JBe*_*rdo 5

如何使用字典(无需对数据进行排序)?

>>> listOfLists = [['key2', 1], ['key1', 2], ['key2', 2], ['key1', 1]]
>>> d = {}
>>> for k,v in listOfLists:
    d.setdefault(k, []).append(v)

>>> d = {k:min(v) for k,v in d.items()}
>>> d
{'key2': 1, 'key1': 1}
Run Code Online (Sandbox Code Playgroud)

如果需要,您可以转换为列表