2 回答
TA贡献1799条经验 获得超9个赞
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)
TA贡献1874条经验 获得超12个赞
像字典这样的东西在这里会更好用吗?
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]]
添加回答
举报
