我想根據另一個串列替換串列中的專案作為參考。
以存盤在字典中的這個示例串列為例:
dict1 = {
"artist1": ["dance pop","pop","funky pop"],
"artist2": ["chill house","electro house"],
"artist3": ["dark techno","electro techno"]
}
然后,我有這個串列作為參考:
wish_list = ["house","pop","techno"]
我的結果應該是這樣的:
dict1 = {
"artist1": ["pop"],
"artist2": ["house"],
"artist3": ["techno"]
}
我想檢查“wishlist”中的任何串列項是否在 dict1 的值之一內。我嘗試了正則運算式,任何。
這是一種只有一個串列而不是多個串列的字典的方法:
check = any(item in artist for item in wish_list)
if check == True:
artist_genres.clear()
artist_genres.append()
我剛剛開始自己??使用 Python,并且正在使用 SpotifyAPI 將我最喜歡的歌曲清理到播放串列中。非常感謝您的幫助!
uj5u.com熱心網友回復:
思路是這樣的,
dict1 = { "artist1" : ["dance pop","pop","funky pop"],
"artist2" : ["house","electro house"],
"artist3" : ["techno","electro techno"] }
wish_list = ["house","pop","techno"]
dict2={}
for key,value in dict1.items():
for i in wish_list:
if i in value:
dict2[key]=i
break
print(dict2)
uj5u.com熱心網友回復:
不需要正則運算式,您可以通過簡單地遍歷串列來擺脫:
wish_list = ["house","pop","techno"]
dict1 = {
"artist1": ["dance pop","pop","funky pop"],
"artist2": ["chill house","electro house"],
"artist3": ["dark techno","electro techno"]
}
dict1 = {
# The key is reused as-is, no need to change it.
# The new value is the wishlist, filtered based on its presence in the current value
key: [genre for genre in wish_list if any(genre in item for item in value)]
for key, value in dict1.items() # this method returns a tuple (key, value) for each entry in the dictionary
}
此實作很大程度上依賴于串列推導(以及字典推導),如果它對您來說是新的,您可能需要檢查它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473218.html
標籤:Python python-3.x 列表 字典
下一篇:傳單無法清除圖層和標記
