python how to search an item in a nested list

冷暖自知 提交于 2019-12-07 09:39:58

问题


say I have this list:

li = [["0", "20", "ar"], ["20", "40", "asdasd"], ["50", "199", "bar"], ["24", "69", "sarkozy"]]

Now, forget about the numbers, they are something that let me recognize the position of string. So basically, given that I have the string "ar" in hand, how can I extract all the lists that contain "ar"?

new_li = [["50", "199", "bar"], ["24", "69", "sarkozy"]]

How can I obtain this list?


回答1:


>>> [x for x in li if 'ar' in x[2]]
[['0', '20', 'ar'], ['50', '199', 'bar'], ['24', '69', 'sarkozy']]


来源:https://stackoverflow.com/questions/6889785/python-how-to-search-an-item-in-a-nested-list

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