Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表理解-在嵌套列表上迭代_Python_List_List Comprehension - Fatal编程技术网

Python 列表理解-在嵌套列表上迭代

Python 列表理解-在嵌套列表上迭代,python,list,list-comprehension,Python,List,List Comprehension,我试图编写一个函数,搜索嵌套列表的全部内容,以返回包含某个单词的所有列表,但这只返回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',

我试图编写一个函数,搜索嵌套列表的全部内容,以返回包含某个单词的所有列表,但这只返回
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”,“天堂的眼泪”,“Rush”]
的第二个元素中有“天堂”,但您正在检查第三个元素(
i[2]
)。Python数组的索引从0开始,而不是从1开始。(但您似乎知道这一点,因为您的第二个示例在
i[2]
中查找“ar”,这是正确的。)


另外,
searchSong()
不返回任何内容,因此默认情况下它总是不返回任何内容。

天堂不在
i[2]
在第一个示例中,它在
i[1]
中。我没有想到在列表理解中使用嵌套for循环,谢谢MaThMaX:)@AJP,这样,无论您的
键位于内部列表的哪个索引上,它都有效。但John Gordon是对的,Python索引总是从0开始
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']]