[英]Python: delete list in list if 1st element in list is duplicated and 2nd element is lowest in lists series
I have a list of lists.我有一个列表列表。 Each list has the same number of elements.
每个列表具有相同数量的元素。 I'd like to delete an entire list if a new list supersedes the old one based on a numeric key in the nth element that all the lists have.
如果新列表基于所有列表具有的第 n 个元素中的数字键取代旧列表,我想删除整个列表。 This numeric key is an increment of 1 starting from 1. Highest key is desired.
此数字键是从 1 开始以 1 为增量递增的。需要最高键。
all = [[123, 1],[456, 1],[789, 1],[123,2],[456, 2],[789,1]]
The last element in each list is the key: 2 supersedes 1 etc... the output desired is:每个列表中的最后一个元素是关键: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)
Would something like a dictionary work better here?像字典这样的东西在这里会更好吗?
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}
In fact, if you know that the second numbers in each pair will never decrease (eg, you won't see something like [123,0]
appear later in the list after [123,2]
) then just converting the list to a dictionary with dict()
should accomplish the same thing.事实上,如果您知道每对中的第二个数字永远不会减少(例如,您将不会看到
[123,0]
之后的列表中出现类似[123,2]
),那么只需将列表转换为带有dict()
字典应该完成同样的事情。 Then you could convert it back to a list if you want.然后,您可以根据需要将其转换回列表。
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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.