如何返回列表中第一个索引项的出现次数?

2024-05-21 01:13:38 发布

您现在位置:Python中文网/ 问答频道 /正文

学习Python并负责返回列表中第一个字母的索引位置。但它必须在任何给定列表的最左上方。例如,“a”将作为索引(0,2)返回。你知道吗

但当我运行代码时,它说找不到字母。假设值代表字母,“.”已在测试仪中定义。如果是“.”,则应返回none

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)

Tags: in列表forvalue字母areafindat
3条回答

我想你想要这样的东西:

def find_spot_values(value,area):
  for row_idx, row in enumerate(area):
      if value in row:
          return (row_idx, row.index(value))

我很巧妙地修改了你的函数,现在它可以工作了:

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))

如果value不在area中,则返回一个带有“coordinates”或None的元组。你知道吗

在内部循环中,还可以使用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

相关问题 更多 >