a_list = [1,2,3,4,[42,'Meaning of life']]
def some_function('Meaning of life')
# insert code here
return 42
我该怎么做?显然,我可以通过以下方式找到“生命的意义”:
for i in a_list:
if i == "Meaning of life":
print i
现在如何找到列表中的元素,然后找到它旁边的元素?
我特意让我的代码在第一个值或整数之后用字符串追加该列表中的所有内容。
答案 0 :(得分:4)
>>> def search(needle, haystack):
for element in haystack:
if not isinstance(element, list):
if element == needle:
return True
else:
found = search(needle, element)
if found:
return element[0]
>>> a_list = [1,2,3,4,[42,'Meaning of life']]
>>> print search('Meaning of life', a_list)
42
>>> print search('Anything else', a_list)
None