我是 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/