繁体   English   中英

列表理解-遍历嵌套列表

[英]List comprehension - Iterating over nested lists

我正在尝试编写一个搜索整个嵌套列表以返回包含某个单词的所有列表的函数,但这只会返回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']]

任何帮助将非常感激 :)

“天堂”出现在["Eric Clapton","Tears in heaven","Rush"]中的第二个元素中,但是您正在检查第三个元素( i[2] )。 Python数组从0开始而不是从1开始索引。(但是您似乎知道这一点,因为第二个示例在i[2]寻找“ ar”,这是正确的。)

另外, searchSong()返回任何内容,因此默认情况下始终返回None。

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']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM