简体   繁体   English

在嵌套列表中使用.index()函数

[英]Using .index() function in nested lists

I am trying to make a program that finds a certain value in a nested list, so I wrote this code: 我试图制作一个在嵌套列表中找到某个值的程序,所以我编写了以下代码:

list = [['S', 'T', 'U', 'T'], ['O', 'P', 'Q', 'R']]

However, when I inputted 但是,当我输入

list.index('O')

It gave me an error message saying 它给我一个错误信息,说

Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
list.index('O')
ValueError: 'O' is not in list

Any ideas? 有任何想法吗?

Well it is really simple, 'O' is not in the list, it only contains the other lists. 好吧,这很简单, 'O'不在列表中,它仅包含其他列表。 Here is an example: 这是一个例子:

list_you_have = [['S', 'T', 'U', 'T'], ['O', 'P', 'Q', 'R']]
print list_you_have.index(['O','P','Q','R']) #outputs 1

Now if you do it like: 现在,如果您这样做:

print list_you_have[1].index('O') # it outputs 0 because you're pointing to 
#list which acctualy contains that 'O' char.

Now a function for nested char search would be 现在,用于嵌套字符搜索的函数将是

def nested_find(list_to_search,char):
    for i, o in enumerate(list_to_search):
        if char in o:
            print "Char %s found at list %s at index %s" % (char, i, o.index(char))

Or maybe an even simpler solution as @zondo commented would be: 或者,也许更简单的解决方案(如@zondo所评论的)是:

def nested_find(list_to_search,char):
    newlist = sum(list_to_search, [])
    if char in newlist:
        print "Char %s is at position %s" % (char, newlist.index(char))

您可以单行解决问题:

print item in reduce(lambda x, y: x + y, nestedlists)

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

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