我正在尝试编写一个完整搜索嵌套列表的函数,以返回包含某个单词的所有列表,但这只返回None
word = "what song?"
def searchSong(mp3_list, word):
search = input((word))
match = [i for i in mp3_list if search in i[2]]
for confirmed in match:
print(confirmed[0],'\n', confirmed[1],'\n', confirmed[2])
print(searchSong(mp3_list, word))
当我进行比较测试时,match
变量仍然不返回任何内容:
mp3_list = [["Eric Clapton","Tears in heaven","Rush"],["Neil Young", "Heart of gold", "Harvest"]]
match = [i for i in mp3_list if 'heaven' in i[2]]
print(match) #returns []
但是这很有效,尽管语法看起来完全一样:
li = [["0", "20", "ar"], ["20", "40", "asdasd"], ["50", "199", "bar"]]
match = [i for i in li if 'ar' in i[2]]
print(match) #returns [['0', '20', 'ar'], ['50', '199', 'bar']]
任何帮助都会非常感激:)
答案 0 :(得分:1)
'天堂'存在于["Eric Clapton","Tears in heaven","Rush"]
的第二个元素中,但您要检查第三个元素(i[2]
)。 Python数组从0开始编号,而不是1.(但你似乎知道这一点,因为你的第二个例子在i[2]
中寻找" ar"这是正确的。)
此外,searchSong()
并未返回任何内容,因此默认情况下它始终返回None。
答案 1 :(得分:1)
mp3_list = [["Eric Clapton","Tears in heaven","Rush"],["Neil Young", "Heart of gold", "Harvest"]]
match = [i for i in mp3_list for j in i if 'heaven' in j]
match
Out[7]: [['Eric Clapton', 'Tears in heaven', 'Rush']]
li = [["0", "20", "ar"], ["20", "40", "asdasd"], ["50", "199", "bar"]]
match = [i for i in li for j in i if 'ar' in j]
match
Out[10]: [['0', '20', 'ar'], ['50', '199', 'bar']]