小编Pat*_*hen的帖子

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

我有一个像这样的清单

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)

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

python

2
推荐指数
1
解决办法
68
查看次数

标签 统计

python ×1