简体   繁体   中英

Delete an item from a list by match not index

I have a nested list that looks like this:

lst = [[1,2,3],["a","b","c"],[4,5,6]]

I would like to delete an item from this list by matching, not by index. For example, how can I delete [4, 5, 6] ?

You could just use lst.remove(...) :

lst = [[1,2,3],["a","b","c"],[4,5,6]]
lst.remove([4,5,6])
print lst

Output:

[[1, 2, 3], ['a', 'b', 'c']]

如果你想删除多个匹配项( lst.remove只会删除第一个匹配项),那么通常更容易使用list-comp重新创建没有你想要的元素的列表...

lst = [el for el in lst if el != [4,5,6]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM