我想在字典列表中获取某些类型的键的所有字典值(例如[' energy']),如下所示:
features = [
[{u'track_href': u'https://api.spotify.com/v1/tracks/56F7imK3kWAzpxl4vmoX5z', u'analysis_url': u'https://api.spotify.com/v1/audio-analysis/56F7imK3kWAzpxl4vmoX5z', u'energy': 0.805, u'liveness': 0.116, u'tempo': 98.026, u'speechiness': 0.0531, u'uri': u'spotify:track:56F7imK3kWAzpxl4vmoX5z', u'acousticness': 0.0142, u'instrumentalness': 0.0287, u'time_signature': 4, u'danceability': 0.685, u'key': 1, u'duration_ms': 318987, u'loudness': -6.393, u'valence': 0.552, u'type': u'audio_features', u'id': u'56F7imK3kWAzpxl4vmoX5z', u'mode': 1}],
[{u'track_href': u'https://api.spotify.com/v1/tracks/1eeCc5LwGurrTFQfpcvjLO', u'analysis_url': u'https://api.spotify.com/v1/audio-analysis/1eeCc5LwGurrTFQfpcvjLO', u'energy': 0.585, u'liveness': 0.397, u'tempo': 140.02, u'speechiness': 0.193, u'uri': u'spotify:track:1eeCc5LwGurrTFQfpcvjLO', u'acousticness': 0.025, u'instrumentalness': 0, u'time_signature': 4, u'danceability': 0.789, u'key': 8, u'duration_ms': 183627, u'loudness': -5.948, u'valence': 0.655, u'type': u'audio_features', u'id': u'1eeCc5LwGurrTFQfpcvjLO', u'mode': 1}],
[{u'track_href': u'https://api.spotify.com/v1/tracks/1C2DJDsfvGxupTQ5sCF5CO', u'analysis_url': u'https://api.spotify.com/v1/audio-analysis/1C2DJDsfvGxupTQ5sCF5CO', u'energy': 0.378, u'liveness': 0.175, u'tempo': 118.026, u'speechiness': 0.13, u'uri': u'spotify:track:1C2DJDsfvGxupTQ5sCF5CO', u'acousticness': 0.0307, u'instrumentalness': 9.93e-05, u'time_signature': 4, u'danceability': 0.899, u'key': 1, u'duration_ms': 236707, u'loudness': -11.322, u'valence': 0.152, u'type': u'audio_features', u'id': u'1C2DJDsfvGxupTQ5sCF5CO', u'mode': 1}],
[{u'track_href': u'https://api.spotify.com/v1/tracks/4e7NiFhKFLLnOCeU5Eg5UI', u'analysis_url': u'https://api.spotify.com/v1/audio-analysis/4e7NiFhKFLLnOCeU5Eg5UI', u'energy': 0.879, u'liveness': 0.288, u'tempo': 88.739, u'speechiness': 0.278, u'uri': u'spotify:track:4e7NiFhKFLLnOCeU5Eg5UI', u'acousticness': 0.0291, u'instrumentalness': 0, u'time_signature': 4, u'danceability': 0.371, u'key': 6, u'duration_ms': 147693, u'loudness': -5.253, u'valence': 0.942, u'type': u'audio_features', u'id': u'4e7NiFhKFLLnOCeU5Eg5UI', u'mode': 0}]
]
这不起作用:
energy_values = [x['energy'] for x in features if x]
我该怎么做?
答案 0 :(得分:0)
列表中的每个元素都是包含一个字典的另一个列表。您应该删除字典周围的方括号或获取每个列表的唯一元素:
energy_values = [x[0]['energy'] for x in features]