回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>所以我已经有一段时间没有真正使用Python了,我已经生锈了——我正在处理一个个人项目,我使用的API返回一个表示歌曲数据的字典列表。我要做的是将返回的歌曲列表缩小到只有评级为5的歌曲(并从列表中删除所有其他歌曲)。我有一些代码下面似乎不工作。它实际上似乎没有删除任何内容,而是打印出整个歌曲列表(在我的例子中,这个列表非常大,大约有11000首歌曲)。你知道吗</p>
<p>作为帮助,我还将发布一个API返回内容的示例(对于一首歌曲):</p>
<pre><code>{
'comment':'',
'rating':'0',
'albumArtRef':[
{
'url': 'http://lh6.ggpht.com/...'
}
],
'artistId':[
'Aod62yyj3u3xsjtooghh2glwsdi'
],
'composer':'',
'year':2011,
'creationTimestamp':'1330879409467830',
'id':'5924d75a-931c-30ed-8790-f7fce8943c85',
'album':'Heritage ',
'totalDiscCount':0,
'title':'Haxprocess',
'recentTimestamp':'1372040508935000',
'albumArtist':'',
'trackNumber':6,
'discNumber':0,
'deleted':False,
'storeId':'Txsffypukmmeg3iwl3w5a5s3vzy',
'nid':'Txsffypukmmeg3iwl3w5a5s3vzy',
'totalTrackCount':10,
'estimatedSize':'17229205',
'albumId':'Bdkf6ywxmrhflvtasnayxlkgpcm',
'beatsPerMinute':0,
'genre':'Progressive Metal',
'playCount':7,
'artistArtRef':[
{
'url': 'http://lh3.ggpht.com/...'
}
],
'kind':'sj#track',
'artist':'Opeth',
'lastModifiedTimestamp':'1330881158830924',
'clientId':'+eGFGTbiyMktbPuvB5MfsA',
'durationMillis':'418000'
}
</code></pre>
<p>我的代码如下:</p>
<pre><code>library = api.get_all_songs()
print("There are",len(library),"items in your music library")
for track in library:
if track['rating'] != 5:
library.remove(track)
print("You have",len(library),"favorite tracks!")
return library
</code></pre>
<p>我添加了“最喜爱的歌曲”数量(以及库中歌曲的数量),以测试和查看我的循环和if语句是否会删除任何内容,但它不会删除任何内容(因为循环前后的数字相同)-我认为这与此有关,因为代码工作正常,否则,它不会删除列表。你知道吗</p>
<p>如果需要任何额外的代码,我将非常乐意提供它。你知道吗</p>