Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建';对于循环';通过字典过滤的?_Python_Dictionary_List Comprehension - Fatal编程技术网

Python 创建';对于循环';通过字典过滤的?

Python 创建';对于循环';通过字典过滤的?,python,dictionary,list-comprehension,Python,Dictionary,List Comprehension,我希望通过包含曲目列表的字典(名为:songs)搜索并附加一个项目。但是,该词典有多个级别和索引。这是我的密码: artists = [] for i in range(len(songs['tracks'])): artist.append(songs['tracks'][i]['artists'][0]['name']) 有没有一种更像Python的方式来编写此代码?我觉得好像在使用 在范围内(len(歌曲['tracks'))不是实现这一点的最佳方法,但它确实起到了作用。与您

我希望通过包含曲目列表的字典(名为:songs)搜索并附加一个项目。但是,该词典有多个级别和索引。这是我的密码:

artists = []

for i in range(len(songs['tracks'])):
     artist.append(songs['tracks'][i]['artists'][0]['name'])
有没有一种更像Python的方式来编写此代码?我觉得好像在使用
在范围内(len(歌曲['tracks'))
不是实现这一点的最佳方法,但它确实起到了作用。

与您的代码相当的一种解决方案可能是

artists = [track['artists'][0]['name'] for track in songs['tracks']]

首先,您在那里所做的实际上是一个“映射”操作(将一个数组的项转换为另一个数组/列表),而不是一个“筛选”操作(从数组/列表中删除与条件匹配的某些项)

其次,你不应该在一个范围内循环。这是一个
for in
循环,而不是传统的
for
循环,因此没有索引。相反,每个迭代都包含列表/数组中的项

artists = []
for track in songs['tracks']:
    artists.append(track['artists'][0]['name'])
您可以使用将其转换为一行程序。它们的共同前提是迭代列表以创建新列表,可能转换结果,也可能过滤结果。他们使用的语法是:

result = [ <transformation> for item in items if <condition> ]
然而,若你们在过滤,那个么if条件就是你们要使用的。比如说

artists_with_long_songs = [ track[artists][0]['name'] for track in songs['tracks'] if track['length'] > 600 ]

缩进是一个错误。我适应了。非常感谢。谢谢你的深入解释。这肯定会帮我的忙!
artists_with_long_songs = [ track[artists][0]['name'] for track in songs['tracks'] if track['length'] > 600 ]