[英]Searching for an item in a nested list and then returning the index of an item
So I was trying to write a function called find_treasure which takes a 2D list as a parameter. 因此,我试图编写一个名为find_treasure的函数,该函数将2D列表作为参数。 The purpose of the function is to search through the 2D list given and to return the index of where the 'x' is located.
该功能的目的是搜索给定的2D列表,并返回“ x”所在位置的索引。
def find_treasure(my_list):
str1 = 'x'
if str1 in [j for i in (my_list) for j in i]:
index = (j for i in my_list for j in i).index(str1)
return(index)
treasure_map = [[' ', ' ', ' '], [' ', 'x', ' '], [' ', ' ', ' ']]
print(find_treasure(treasure_map))
However, I can't seem to get the function to return the index, I tried using the enumerate function too but either I was using it wrongly. 但是,我似乎无法获得返回索引的函数,我也尝试使用枚举函数,但是我使用它的方式有误。
Using enumerate
使用
enumerate
def find_treasure(my_list):
str1 = 'x'
for i,n in enumerate(my_list):
for j, m in enumerate(n):
if m == str1:
return (i, j)
treasure_map = [[' ', ' ', ' '], [' ', 'x', ' '], [' ', ' ', ' ']]
print(find_treasure(treasure_map))
Output: 输出:
(1, 1)
Using index
function. 使用
index
功能。
def find_treasure(my_list):
str1 = 'x'
for i,n in enumerate(my_list):
try:
return (i, n.index(str1))
except ValueError:
pass
treasure_map = [[' ', ' ', ' '], [' ', 'x', ' '], [' ', ' ', ' ']]
print(find_treasure(treasure_map))
Output 输出量
(1, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.