查找列表中最后出现的字符

2024-04-25 22:30:01 发布

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

我正在编写一个函数,需要返回列表中某个字符最后一次出现的行和列。如果字符不在列表列表中,函数应该返回None。函数忽略或跳过第一次出现,然后将最后一次出现的行和列作为有序对返回。你知道吗

Example: 

lst = [['.','.','.','e'],
       ['A','A','.','e'],
       ['.','.','.','e'],
       ['.','X','X','X'],
       ['.','.','.','.'],
       ['.','y','Z','Z']]

#For this list of lists the function should return (5,3) for Z since it is in the 6th list, 
#and is the 6th value (python starts the count at 0) and for X it should return (3,3)

我认为我当前的代码找到了字符第一次出现的行和列,但没有找到最后一次出现的行和列。如何指示Python忽略第一次出现的内容,而返回最后一次出现的行和列?你知道吗

代码:

def get_far_end(symbol,lot):
    for i in range(len(lot)):
        for j in lot[i]:
            if j == symbol:
                return i ,lot[i].index(j)   

Tags: andthe函数代码in列表forreturn
3条回答

我想你对任何字符都感兴趣,除了“.”。如果是这样的话,那么您可以使用以下词典:

lst = [['.','.','.','e'],
       ['A','A','.','e'],
       ['.','.','.','e'],
       ['.','X','X','X'],
       ['.','.','.','.'],
       ['.','y','Z','Z']]

out_dict = {}

for i in range(len(lst)):
        for j in range(len(lst[i])):
            if lst[i][j] is not '.':
                out_dict[lst[i][j]] = [i,j]


print(out_dict)
# {'Z': [5, 3], 'y': [5, 1], 'X': [3, 3], 'A': [1, 1], 'e': [2, 3]}

自始至终向后:

def get_far_end(symbol,lot):
    for i in range(len(lot)-1,-1,-1):
        for j in range(len(lot[i])-1,-1,-1):
            if lot[i][j] == symbol:
                return i ,j
    return None   

您的算法的问题是,当您找到元素的第一个匹配项时,您将返回fas。你知道吗

所以您应该做的是,当您找到j==symbol时,保存这两个索引并继续调整您的矩阵

在所有循环之后,您将拥有符号的最后一次出现。。你知道吗

或者,第二个方法是,从末尾开始,运行逆矩阵,在这种情况下,可以返回j==symbol的第一次出现

相关问题 更多 >