python-3.x - 如何使用该列表作为该函数的参数?

标签 python-3.x spotify spotipy

我是 Python 新手,我正在使用它通过 Spotipy 编写 Spotify 应用程序。基本上,我有一个名为 topTracks 的轨道字典。我可以访问轨道及其名称/ID 等内容

topSongs['items'][0]
topSongs['items'][3]['id']
topSongs['items'][5]['name']

所以我正在尝试使用一个函数:

recommendations(seed_artists=None, seed_genres=None, seed_tracks=None, limit=20, country=None, **kwargs)

通过这个函数,我尝试使用seed_tracks,它需要一个轨道ID 列表。所以理想情况下我想输入 topSongs['items'][0]['id'], topSongs['items'][1]['id'], topSongs['items'][2]['id']等等。我该怎么做?我已经阅读过有关 * 运算符的内容,但我不确定如何使用它或者它是否适用于此处。

最佳答案

您可以尝试如下所示的操作。

ids = [item["id"] for item in topSongs["items"]]

Here, I have just formed a simple example.

>>> topSongs = {
...     "items": [
...         {
...             "id": 1,
...             "name": "Alejandro"
...         },
...         {
...             "id": 22,
...             "name": "Waiting for the rights"
...         }
...     ]
... }
>>> 
>>> seed_tracks = [item["id"] for item in topSongs["items"]]
>>> 
>>> seed_tracks
[1, 22]
>>> 

关于使用 * 运算符的 Imp 注释 »

在这种情况下使用

* 运算符,但为此,您需要形成一个包含函数获取的数据列表的列表/元组。类似的东西

You have to form all the variables like seed_tracks above.

data = [seed_artists, seed_genres, seed_tracks, limit, country]   

最后,

recommendations(*data)

关于使用 ** 运算符的 Imp 注释 »

如果您愿意使用**运算符,数据将如下所示

data = {"seed_artists": seed_artists, "seed_genres": seed_genres, "seed_tracks": seed_tracks, "limit": limit, "country": country} 

最后,

recommendations(**data)

关于python-3.x - 如何使用该列表作为该函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55978846/

相关文章:

python - spotipy授权代码流程

python - 在 AWS 上使用 Spotipy 通过 Python 对 Spotify 进行用户身份验证

python - 延迟加载 python 子模块,importlib 第一次失败

python - discord.py 机器人重写 AttributeError : 'Bot' object has no attribute 'send_message'

javascript - 如何在新的 Spotify Web api 上获取用户的关注者和用户的关注者?

ios - Spotify session 管理

python - Spotify - 删除使用 None 值创建的访问 token

python - 获取满足条件的行的列最大值

python - Argparse 与函数的交互

android - Libspotify 或适用于 Android 应用程序的新 SDK?