编写函数,接收一个字符串,返回其中每个字符的最后一次出现,并按每个字符最后一次出现的先后顺序依次存入列表。例如,对于字符串'abcda'的处理结果为['b', 'c', 'd', 'a'],而字符串'abcbda'的处理结果为['c', 'b', 'd', 'a']。
时间: 2023-10-23 11:14:18 浏览: 203
可以通过遍历字符串,将每个字符最后一次出现的位置记录在一个字典中,然后按照每个字符最后一次出现的位置排序,最后返回排序后的字符列表。
下面是实现的代码:
```python
def last_occurrence(s):
last = {}
for i, c in enumerate(s):
last[c] = i
return sorted(last.keys(), key=lambda x: last[x])
# 测试
print(last_occurrence('abcda')) # ['b', 'c', 'd', 'a']
print(last_occurrence('abcbda')) # ['c', 'b', 'd', 'a']
```
阅读全文
相关推荐
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![dll](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)