list1 = [
{'id': 1, 'country': 'Italy'},
{'id': 2, 'country': 'Spain'},
{'id': 3, 'country': 'Japan'}
]
I use this code to remove from list1
every dictionary that has country != Italy
:
list2 = [element for element in list1 if element['country'] == 'Italy']
But I to include in list2
dictionaries which country == 'Italy'
AND country == 'Spain'
and remove all the others (or even better pop them from list1
without creating another one). How can I do this in one line=
如果您真的想要单线,则可以将列表理解与就地列表更新一起使用:
list1[:] = [d for d in list1 if d['country'] in ('Spain', 'Italy')]
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.