我有一个表格中的数据集:
control_albums_tracks[a][0]['items'][b]['id']
a
和b
有哪些项目我想迭代。并且b
包含一些None
值。
无论我尝试什么,我都无法从数据中提取song['id']
值。
control_track_ids = [song['id'] for song in album[0]['items']
for album in control_albums_tracks if song['id'] is not None]
我还试过以下各种变体来尝试容纳None
值:
control_track_ids = []
for album in control_albums_tracks:
for song in album[0]['items']:
control_track_ids.append(song['id'])
有没有正确的方法可以解决这个问题?我想将值提取到列表中(control_track_ids
)。
答案 0 :(得分:0)
看起来你的两个for
循环子句的顺序错误了。外环应该是第一个:
control_track_ids = [song['id'] for album in control_albums_tracks
for song in album[0]['items']
if song['id'] is not None]
您也可能希望if song is not None
代替if song['id'] is not None
,但该部分不太明确(它取决于None
出现的级别)
答案 1 :(得分:0)
知道了。
control_track_ids = []
try:
for album in control_albums_tracks:
for song in album[0]['items']:
control_track_ids.append(song['id'])
except TypeError:
album = None