I have a problem with multiple conditions with list:
listionary = [{u'city': u'paris', u'id': u'1', u'name': u'paul'},
{u'city': u'madrid', u'id': u'2', u'name': u'paul'},
{u'city': u'berlin', u'id': u'3', u'name': u'tom'},
{u'city': u'madrid', u'id': u'4', u'name': u'tom'}]
I try to delete items that meet both conditions simultaneously.
[elem for elem in listionary if (elem.get('name')!='paul' and elem.get('city')!='madrid')]
In this case element is removed if meet at least one condition, I try to do it in several ways, any ideas?
Expected output:
[{u'city': u'paris', u'id': u'1', u'name': u'paul'}
{u'city': u'berlin', u'id': u'3', u'name': u'tom'}
{u'city': u'madrid', u'id': u'4', u'name': u'tom'}]
I would like to remove element which meet both conditions.
Try changing the and
to or
.
[elem for elem in listionary if (elem.get('name')!='paul' or elem.get('city')!='madrid')]
Remember de morgan's laws. Informally: when you negate a boolean expression, you have to switch and
with or
in addition to switching "==" with "!=".
Your condition should have been like this
[e for e in data if not (e.get('name') == 'paul' and e.get('city') == 'madrid')]
Output
[{u'city': u'paris', u'id': u'1', u'name': u'paul'},
{u'city': u'berlin', u'id': u'3', u'name': u'tom'},
{u'city': u'madrid', u'id': u'4', u'name': u'tom'}]
This checks if the current element's name
is paul
and city
is madrid
. If both the conditions are satisfied, the not
outside will flip it, so you will get False
and the item will be omitted.
Basically you are checking if the current item is the one which you don't want and make the if
condition fail if it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With