2 回答

TA貢獻1799條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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}
事實上,如果您知道每對中的第二個數(shù)字永遠不會減少(例如,您將不會[123,0]在 之后的列表中看到類似的內(nèi)容[123,2]),那么只需將列表轉換為字典 就dict()可以完成同樣的事情。然后,您可以根據(jù)需要將其轉換回列表。
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]]
添加回答
舉報