我正在尝试创建一个在嵌套列表中找到某个值的程序,所以我编写了这段代码:
list = [['S', 'T', 'U', 'T'], ['O', 'P', 'Q', 'R']]
然而,当我输入
list.index('O')
它给了我一条错误信息
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
list.index('O')
ValueError: 'O' is not in list
有什么想法吗?
答案 0 :(得分:2)
这很简单,'O'
不在列表中,它只包含其他列表。这是一个例子:
list_you_have = [['S', 'T', 'U', 'T'], ['O', 'P', 'Q', 'R']]
print list_you_have.index(['O','P','Q','R']) #outputs 1
现在,如果你这样做:
print list_you_have[1].index('O') # it outputs 0 because you're pointing to
#list which acctualy contains that 'O' char.
现在嵌套字符搜索的函数将是
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))
或者@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))
答案 1 :(得分:0)
您可以单行解决问题:
<span>
<img src="http://lorempixel.com/300/150/sports/1">
</span>