简体   繁体   中英

Remove list items from within list of list

How do I remove all 'd' and 'e'

abc = [('a','b','c','d','e'), ('a','b','c','d','e'), 
 ('a','b','c','d','e'), ('a','b','c','d','e')]

abc.remove('d')

ValueError: list.remove(x): x not in list

abc.remove('d', 'e')

TypeError: remove() takes exactly one argument (2 given)

finalList = []
for l in abc:
    finalList.append([i[3] for i in l])

IndexError: string index out of range

You can use a nested list comprehension to check if any of the sub elements are in your "blacklist" and keep the rest.

>>> [tuple(i for i in sub if i not in {'d', 'e'}) for sub in abc]
[('a', 'b', 'c'), ('a', 'b', 'c'), ('a', 'b', 'c'), ('a', 'b', 'c')]

You cannot remove an element from a tuple. However, the following procedure can solve your problem.

abc = [('a','b','c','d','e'), ('a','b','c','d','e'), ('a','b','c','d','e'), ('a','b','c','d','e')]
l = [] // Creating an empty list

// Appending all tuples of abc in l as LISTS
for item in abc:
    l.append(list(item))
// Removing the unnecessary elements

for item in l:
    item.remove('d')
    item.remove('e')
print(l)
l = [('a','b','c','d','e'), ('a','b','c','d','e'), 
 ('a','b','c','d','e'), ('a','b','c','d','e')]

print ([tuple(s for s in x if s not in ['d','e']) for x in l])

Output:

[('a', 'b', 'c'), ('a', 'b', 'c'), ('a', 'b', 'c'), ('a', 'b', 'c')]

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