I have been reading a few other SO articles and understand bits and pieces of what I am trying to accomplish, but I have yet to settle on an answer that encompasses my requirements.
I know how to remove a single item from a simple list like [1,2,3,4], but I have a more complex list, where the order/contents are not predictable, that I am trying to remove an element from:
list = [{u'role': u'OWNER', u'userByEmail': u'test1@email.com'}, {u'specialGroup': u'projectWriters', u'role': u'READER'}, {u'specialGroup': u'projectOwners', u'role': u'READER'}, {u'specialGroup': u'projectReaders', u'role': u'READER'}, {u'role': u'READER', u'userByEmail': u'test2@email.com'}, {u'view': {u'projectId': u'project-01', u'tableId': u'testing_tbl_2', u'datasetId': u'test2'}}, {u'view': {u'projectId': u'project-01', u'tableId': u'testing_tbl_3', u'datasetId': u'dtest2'}}, {u'view': {u'projectId': u'project-01', u'tableId': u'view1', u'datasetId': u'test2'}}]
I need to remove:
{u'role': u'READER', u'userByEmail': u'test1@email.com'}
and return the new list without that key/value element present. I can do something like this (I would prefer this format) but this only returns the key/value element that the filter is looking for.
>>> filter(lambda row: row.has_key('userByEmail') and row['userByEmail'] == 'test1@email.com', list)
[{u'role': u'OWNER', u'userByEmail': u'test1@email.com'}]
How do I remove the element from the list and then print out the new list with the filtered element missing?
Invert the condition to
not (...)
so
filter(lambda row: row.has_key('userByEmail') and row['userByEmail'] == 'test1@email.com', list)
becomes
filter(lambda row: not (row.has_key('userByEmail') and row['userByEmail'] == 'test1@email.com'), list)
我不确定,但也许与next()
:
list.remove(next(obj for obj in list if obj == {u'role': u'READER', u'userByEmail': u'test1@email.com'}))
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.