您当前的位置:首页 > 计算机 > 编程开发 > Python

Python花式编程案例锦集(1)

时间:12-28来源:作者:点击数:

问题描述:给定任意字符串,查找其中每个字符的最后一次出现,并按每个字符最后一次出现的先后顺序依次存入列表。例如对于字符串'abcda'的处理结果为['b', 'c', 'd', 'a'],而字符串'abcbda'的处理结果为['c', 'b', 'd', 'a']。

# 测试字符串

s = 'aaaabcdawerasdfasdfwerngsnnvAAAweB3a'

# 笨办法

result = []

for ch in s:

    if ch in result:

        result.remove(ch)

    result.append(ch)

print(result)

# 使用正则表达式

import re

print(re.findall(r'(\w)(?!.*\1)', s))

# 使用有序字典

from collections import OrderedDict

print(list(reversed(OrderedDict.fromkeys(reversed(s)))))

运行结果:

['b', 'c', 'd', 'f', 'r', 'g', 's', 'n', 'v', 'A', 'w', 'e', 'B', '3', 'a']

['b', 'c', 'd', 'f', 'r', 'g', 's', 'n', 'v', 'A', 'w', 'e', 'B', '3', 'a']

['b', 'c', 'd', 'f', 'r', 'g', 's', 'n', 'v', 'A', 'w', 'e', 'B', '3', 'a']

你还有别的好思路吗?欢迎提供更多思路。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门