[英]How can I find the indices of the sublists in my list with the same elements?
我有一个不同的子列表的列表:
lst = [
['Alex', 'Peeters', 22],
['Jim', 'West', 22],
['Alex', 'Wesley', 25],
['Jim', 'West', 24]
]
如何在列表中找到名字和姓氏相同的子列表的索引,以便删除年龄最大的子列表?
因此,在这种情况下, lst[1][0] == lst[3][0] and lst[1][1] == lst[3][1]
因为lst[1][2] < lst[3][2]
lst.remove[3]
我已经知道了,但是然后我得到了IndexError
因为我的len(lst)
更改了删除操作。
for i in range (len(lst)):
for j in range (len(lst)):
if lst[i][0] == lst [j][0] and lst[i][1] == lst [j][1] and i != j:
if lst[i][2] < lst[j][2]:
lst.remove(lst[j])
else:
lst.remove(lst[i])
如果元素的顺序不重要,则可以在列表理解中使用itertools.groupby
>>> [min(y) for x,y in itertools.groupby(sorted(lst), key = lambda x:x[:2])]
[['Alex', 'Peeters', 22], ['Alex', 'Wesley', 25], ['Jim', 'West', 22]]
您可以将要删除的子列表存储在另一个列表中,并在找到所有要删除的列表之后将其删除。
to_remove = []
for i in range (len(lst)):
for j in range (len(lst)):
if lst[i][0] == lst [j][0] and lst[i][1] == lst [j][1] and i != j:
if lst[i][2] < lst[j][2]:
to_remove.append(j)
else:
to_remove.append(i)
for sublist in to_remove:
lst.pop(sublist)
这使它有点冗长,但更易于理解和调试。
这可能是实现此目的的一种方法:
lst = [['Alex', 'Peeters', 22], ['Jim', 'West', 22],['Alex', 'Wesley', 25],['Jim', 'West', 24]]
result = []
for each in set(map(lambda x: tuple(x[:2]), lst)):
_min_lst = []
for i in range(len(lst)):
if each[0] in lst[i] and each[1] in lst[i]:
_min_lst.append(lst[i][2])
result.append(list(each)+[min(_min_lst)])
print result
产量:
[['Alex', 'Peeters', 22], ['Jim', 'West', 22], ['Alex', 'Wesley', 25]]
另一种解决方案
items_to_remove = []
i, j = 0, 0
for x in lst:
j = 0
for y in lst:
if x[0] == y[0] and x[1] == y[1] and i != j and x[2] >= y[2]:
items_to_remove.append(x)
j += 1
i += 1
for item in items_to_remove:
lst.remove(item)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.