将列表推导与 OR 子句一起使用



所以我正在尝试将字典转换为列表,同时我想获取不包含某些关键字的键。我尝试做这样的事情(见下文(,但它似乎不起作用。有人有任何想法如何做到这一点吗?

[(key,value) for key, value in album.items() if ('available_markets' not in key) or ('images' not in key)]

编辑:专辑数据应如下所示:

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'}

我的尝试又回到了我身上:

[('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')]

我缩短了专辑词典,但可用市场的范围可以从 1 到 70+,图像可以是 1 到 3。我只是想在新列表中过滤掉这些键。

将整个操作包装在not而不是每个单独的部分:

[kv for kv in album.items()
if not ('available_markets' in key or 'images' in key)]

或者,使用and

[kv for kv in album.items()
if 'available_markets' not in key and 'images' not in key]

感谢您@chepner指出在组合阴性测试时and的使用。

最新更新