Python 如何返回列表中项目的第一个索引出现?
学习Python并负责返回列表中第一个字母的索引位置。但它必须位于任何给定列表的最左上方。例如,“a”将作为索引(0,2)返回 但当我运行代码时,它说找不到该字母。假设值表示字母,“.”已在测试仪中定义。如果是“.”,则应返回nonePython 如何返回列表中项目的第一个索引出现?,python,python-3.x,Python,Python 3.x,学习Python并负责返回列表中第一个字母的索引位置。但它必须位于任何给定列表的最左上方。例如,“a”将作为索引(0,2)返回 但当我运行代码时,它说找不到该字母。假设值表示字母,“.”已在测试仪中定义。如果是“.”,则应返回none area1 = [['.', 'a', 'a', 'D', 'D'], ['.', '.', 'a', '.', '.'], ['A', 'A', '.', 'z', '.'], ['.', '.', '
area1 = [['.', 'a', 'a', 'D', 'D'],
['.', '.', 'a', '.', '.'],
['A', 'A', '.', 'z', '.'],
['.', '.', '.', 'z', '.'],
['.', '.', 'C', 'C', 'C']]
def find_spot_values(value,area):
for row in area:# Looks at rows in order
for letter in row:# Looks at letter strings
if value == letter in area: #If strings are equal to one another
area.index(value)# Identifies index?
find_spot_values('D',area1)
我想你想要这样的东西:
def find_spot_values(value,area):
for row_idx, row in enumerate(area):
if value in row:
return (row_idx, row.index(value))
我粗略地修改了you函数,现在它可以工作了:
area1 = [['.', 'a', 'a', 'D', 'D'], ['.', '.', 'a', '.', '.'], ['A', 'A', '.', 'z', '.'], ['.', '.', '.', 'z', '.'], ['.', '.', 'C', 'C', 'C']]
def find_spot_values(value,area):
# Loop through the rows, id_row contains the index and row the list
for id_row, row in enumerate(area):# Looks at rows in order
# Loop through all elements of the inner list
for idx, letter in enumerate(row):
if value == letter: #If strings are equal to one another
return (id_row, idx)
# We returned nothing yet --> the letter isn't in the lists
return None
print(find_spot_values('D',area1))
如果值
不在区域
,则返回带有“坐标”或无的元组
在内部循环中,还可以使用index()
函数。在这种情况下,如果列表中不包含字母,则必须处理例外情况。只需对代码进行最小的更改
def find_spot_values(value, area):
for row in area: # Looks at rows in order
for letter in row: # Looks at letter strings
if value == letter: # If strings are equal to one another
return area.index(row), row.index(letter) # Identifies indices
感谢您的简单解释,还有什么方法可以扭转这种情况并在列表中选择最新的字符串吗?