Python:列表中的删除列表如果列表中的第一个元素重复,并且第二个元素在列表系列中最低



我有一个列表。每个列表具有相同数量的元素。如果新列表根据所有列表中的nth元素中的数字键取代旧列表,我想删除整个列表。该数字键是从1开始的增量为1的增量。最高键是需要的。

all = [[123, 1],[456, 1],[789, 1],[123,2],[456, 2],[789,1]]

每个列表中的最后一个元素是关键:2取代1等...所需的输出是:

[[123,2],[456,2],[789,1]]
for x in list(all):
    for y in list(all):
        if y[0] == x[0] and y[1] <= x[1] and y is not x:
            all.remove(y)

诸如字典之类的东西在这里可以更好地工作吗?

all = [[123, 1],[456, 1],[789, 1],[123,2],[456, 2],[789,1]]
as_dict = {}
for item in all:
    if not (item[0] in as_dict and as_dict[item[0]] > item[1]):
        as_dict[item[0]] = item[1]
print(as_dict)
# Returns {123: 2, 456: 2, 789: 1}

实际上,如果您知道每对中的第二个数字将永远不会减少(例如,您不会看到 [123,0]之类的东西出现在 [123,2]之后的列表中),则只需将列表转换为使用dict()的字典应该完成一样的东西。然后,如果需要,您可以将其转换回列表。

d = dict(all)  # This is {123: 2, 456: 2, 789: 1}
newlist = [ [k,d[k]] for k in d] # This is [[123, 2], [456, 2], [789, 1]]

最新更新