使用列表作为参考检查列表项中的字符串

Check for string in list items using list as reference

我想根据另一个列表替换列表中的项目作为参考。

以存储在字典中的列表为例:

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 的值之一内。我尝试使用正则表达式,任何。

这是一种只有 1 个列表而不是多个列表的字典的方法:

check = any(item in artist for item in wish_list)
    if check == True:
        artist_genres.clear() 
        artist_genres.append()

我刚开始自己​​ Python,正在尝试使用 SpotifyAPI 将我最喜欢的歌曲清理到播放列表中。非常感谢您的帮助!

不需要正则表达式,您可以通过简单地遍历列表来摆脱困境:

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
}

此实现很大程度上依赖于 list comprehensions (and also dictionary comprehensions),您可能需要检查它是否对您来说是新的。

思路是这样的,

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)