Check if list contains another list in python

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

I have two lists, one containing lists of album, file pairs and the other containing only info about one photo - album (at position 0) and file (at position 1)

photos = [["Trip to Thailand", "IMG_001.jpg"], ["Latvia 2010", "IMG_001.jpg"]] photo = ["Latvia 2010", "IMG_001.jpg"] 

How to check if photo list is in photos list? Similarly like photo in photos for strings.

Position of album, file doesn't matter since there won't be any file equal to album.

回答1:

Similarly like photo in photos for strings. Not just similarly, exactly like that. photo in photos works for lists inside lists too:

>>> photos = [["Trip to Thailand", "IMG_001.jpg"], ["Latvia 2010", "IMG_001.jpg"]] >>> photo = ["Latvia 2010", "IMG_001.jpg"] >>> photo in photos True 

Membership testing against a list simply iterates over the list and uses == equality testing with each element to see if there is a match. Your photo list tests as equal to the second element:

>>> photos[1] == photo True 

because all strings in both lists are equal.



回答2:

photos = [["Trip to Thailand", "IMG_001.jpg"], ["Latvia 2010", "IMG_001.jpg"]] photo = ["Latvia 2010", "IMG_001.jpg"] print (photo in photos) True 

There is no difference, you would check exactly as you would for a string.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!