[英]python - using list comprehension with an or clause
So I'm trying to convert a dictionary into a list, and at the same time I want to get the keys that do not contain certain keywords. 因此,我试图将字典转换为列表,同时我想获取不包含某些关键字的键。 I tried doing something like this(see below) but it doesn't seem to work.
我试图做这样的事情(见下文),但似乎没有用。 Anyone have any ideas how to do this?
任何人有任何想法如何做到这一点?
[(key,value) for key, value in album.items() if ('available_markets' not in key) or ('images' not in key)]
EDIT: album data should look something like this: 编辑:专辑数据应如下所示:
album ={'album_group': 'album', 'album_type': 'album', 'artists_0_external_urls_spotify': 'https://open.spotify.com/artist/3WrFJ7ztbogyGnTHbHJFl2', 'artists_0_href': 'https://api.spotify.com/v1/artists/3WrFJ7ztbogyGnTHbHJFl2', 'artists_0_id': '3WrFJ7ztbogyGnTHbHJFl2', 'artists_0_name': 'The Beatles', 'artists_0_type': 'artist', 'artists_0_uri': 'spotify:artist:3WrFJ7ztbogyGnTHbHJFl2', 'available_markets_0': 'AD', 'available_markets_1': 'AE', 'images_1_width': 300, 'images_2_height': 64, 'images_2_url': 'https://i.scdn.co/image/f6e12b2ef70abf43d110e5c79810655c7c3fae98', 'images_2_width': 64, 'name': 'The Beatles', 'release_date': '2018-11-09', 'release_date_precision': 'day'}
My attempt returned to me: 我的尝试又回到了我身边:
[('album_group', 'album'), ('album_type', 'album'),
('artists_0_external_urls_spotify',
'https://open.spotify.com/artist/3WrFJ7ztbogyGnTHbHJFl2'),
('artists_0_href',
'https://api.spotify.com/v1/artists/3WrFJ7ztbogyGnTHbHJFl2'),
('artists_0_id', '3WrFJ7ztbogyGnTHbHJFl2'),
('artists_0_name', 'The Beatles'),
('artists_0_type', 'artist'),
('artists_0_uri', 'spotify:artist:3WrFJ7ztbogyGnTHbHJFl2'),
('available_markets_0', 'AD'),
('available_markets_1', 'AE'),
('images_1_width', 300),
('images_2_height', 64),
('images_2_url',
'https://i.scdn.co/image/f6e12b2ef70abf43d110e5c79810655c7c3fae98'),
('images_2_width', 64),
('name', 'The Beatles'),
('release_date', '2018-11-09'),
('release_date_precision', 'day')]
I shorten the album dict but available markets can be a range from 1 to 70+ and images can be from 1 to 3. I'm just trying to filter out those keys in the new list. 我缩短了专辑的时间,但可用市场的范围可能从1到70+,图像的范围可能是1到3。我只是想在新列表中过滤掉这些键。
Wrap the whole operation in not
instead of each individual part: not
将整个操作包装在各个部分中:
[kv for kv in album.items()
if not ('available_markets' in key or 'images' in key)]
Alternatively, use and
: 或者,使用
and
:
[kv for kv in album.items()
if 'available_markets' not in key and 'images' not in key]
Thank you to @chepner for pointing out the use of and
when combining negative tests. 感谢@chepner指出负面测试的使用
and
组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.