在多维列表中搜索元素不起作用.任何线索 [英] Search of Element inside a multi-dimensional List Not Working. Any Clue

查看:28
本文介绍了在多维列表中搜索元素不起作用.任何线索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在多维列表中搜索元素,但它不起作用.我的搜索有什么问题吗??下面是简单的代码,我尝试使用 'in' 和 'any' 进行搜索,但没有用.

I am trying to search for an element inside a multi-dimensional list, but its not working. Anything wrong in my search ?? Below is the simple code and I tried searching using 'in' and 'any' but didnt work..

list1 = []
list1.append([['hello'], ['blue'], ['bla']])

print list1

list1.append([['hello'], ['blue'], ['bla']])
print list1

#if 'hello' in list1:
if any('hello' in x for x in list1):
    print "Found Hello"
else:
    print "Not Found Hello"

猜猜我在做什么错误??请分享您的意见/意见.

Any guess whats the error I am doing ?? Kindly share in your inputs/comments.

感谢 Adv !维摩

推荐答案

如果 list1 应该是一个列表列表,那么问题是你将一个列表附加到 list1code>,在这种情况下,使用 extend 代替.

If list1 should be a list of lists, then the problem is that you are appending a list to list1, in this case, use extend instead.

如果你想在一个嵌套列表(任意数量级)中搜索一个项目,你可以使用这个函数

If you want to search a item in a nested list (any number of levels), you can use this function

def in_nested_list(item, x):
    if not isinstance(x, list):
        return x == item
    else:
        return any(in_nested_list(item, ix) for ix in x)

list1 = []
list1.append([['hello'], ['blue'], ['bla']])

print list1

list1.append([['hello'], ['blue'], ['bla']])
print list1

#if 'hello' in list1:
if in_nested_list('hello', list1):
    print "Found Hello"
else:
    print "Not Found Hello"

这篇关于在多维列表中搜索元素不起作用.任何线索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆