You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Spotify API返回的数组中提取spotify:artist:对应值?

解决Spotify API艺术家ID提取问题

先明确API返回数据结构

Spotify API返回的艺术家数据数组,常见两种结构:

  1. 每个元素是包含uri字段的对象:
artists_id = [
    {"uri": "spotify:artist:4RB42AM4VqzdHRQiVbzDU1"},
    {"uri": "spotify:artist:6n18eBRlVxd4v4YnbbYlvs"},
    {"uri": "spotify:artist:4Bv3GYUzNM11yYGQslJOkp"}
]
  1. 每个元素直接是URI字符串:
artists_id = [
    "spotify:artist:4RB42AM4VqzdHRQiVbzDU1",
    "spotify:artist:6n18eBRlVxd4v4YnbbYlvs",
    "spotify:artist:4Bv3GYUzNM11yYGQslJOkp"
]

对应提取方法

针对对象数组的提取

用列表推导式拆分URI字符串获取ID:

artist_ids = [item["uri"].split(":")[-1] for item in artists_id]
print(artist_ids)

输出结果:
['4RB42AM4VqzdHRQiVbzDU1', '6n18eBRlVxd4v4YnbbYlvs', '4Bv3GYUzNM11yYGQslJOkp']

针对字符串数组的提取

同样用列表推导式拆分:

artist_ids = [uri.split(":")[-1] for uri in artists_id]
print(artist_ids)

输出结果同上。

原代码失败原因

你写的artists_id[spotify:artist]存在两个问题:

  • Python列表的索引只能是整数或切片,不能用这种非字符串格式的标识
  • 即使是字典取值,也需要用字符串类型的键(比如item["uri"]),而非直接写spotify:artist

内容的提问来源于stack exchange,提问作者Sebastiaan Castenmiller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 09:15:55