使用list作为引用检查列表项中的字符串



我想根据另一个列表替换列表中的项作为引用。

以字典中的列表为例:

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的一个值中。我试过用regex, any.

这是一个只有一个列表的方法,而不是一个包含多个列表的字典:

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

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

这个想法是这样的,

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)

不需要正则表达式,您可以通过简单地遍历列表来解决:

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
}

这个实现很大程度上依赖于列表推导式(也包括字典推导式),如果你对它不熟悉,你可能想检查一下。