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

我有一份清单。每个列表具有相同数量的元素。如果新列表基于所有列表具有的第 n 个元素中的数字键取代旧列表,我想删除整个列表。此数字键是从 1 开始以 1 为增量递增的。需要最高键。

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

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

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


Smart猫小萌
浏览 202回答 2
2回答

扬帆大鱼

for x in list(all):&nbsp; &nbsp; for y in list(all):&nbsp; &nbsp; &nbsp; &nbsp; if y[0] == x[0] and y[1] <= x[1] and y is not x:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; all.remove(y)

HUWWW

像字典这样的东西在这里会更好用吗?all = [[123, 1],[456, 1],[789, 1],[123,2],[456, 2],[789,1]]as_dict = {}for item in all:&nbsp; &nbsp; if not (item[0] in as_dict and as_dict[item[0]] > item[1]):&nbsp; &nbsp; &nbsp; &nbsp; as_dict[item[0]] = item[1]print(as_dict)# Returns {123: 2, 456: 2, 789: 1}事实上,如果您知道每对中的第二个数字永远不会减少(例如,您将不会[123,0]在 之后的列表中看到类似的内容[123,2]),那么只需将列表转换为字典 就dict()可以完成同样的事情。然后,您可以根据需要将其转换回列表。d = dict(all)&nbsp; # This is {123: 2, 456: 2, 789: 1}newlist = [ [k,d[k]] for k in d] # This is [[123, 2], [456, 2], [789, 1]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python