python - 按列表拆分字符串
问题描述
如何根据给定列表中的变量拆分字符串?
(我使用的是 python 2.7)。
例如:
given_list = ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b']
st="c#cd#e"
预期结果:
new_list = ['c#','c', 'd#', 'e']
问题是一些变量以相同的字母开头。该程序不会查看# 符号,而是查看第一个字母。
在此先感谢您的帮助。
解决方案
用于'|'.join()
从您的 given_list 中创建一个正则表达式模式,并使用带有“#”的那些注释对列表进行排序的技巧首先按逆字母顺序排列
import re
given_list = ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b']
given_list= sorted(given_list, reverse=True)
# ['g#', 'g', 'f#', 'f', 'e', 'd#', 'd', 'c#', 'c', 'b', 'a#', 'a']
st="c#cd#e"
new_list = re.findall('|'.join(given_list), st)
print(new_list)
# ['c#', 'c', 'd#', 'e']
编辑:reverse=True
按照sorted(given_list,reverse=True)
@HenryYik 的建议使用
推荐阅读
- javascript - 反应JS | 无法获取 ComponentDidMount 上的数据
- c# - 视觉工作室 2019 | “Microsoft.VisualStudio.Azure.Containers.Tools.Targets”NuGet 包 | “在此来源中不可用”
- c - 理解对象表示
- design-patterns - 立面模式需要示例
- visual-studio-2017 - 引用的库使用 VS 2017 在 Nuspec 中注册为其他 nuget 引用
- mysql - MySQL 服务器 8.0.15 写入配置文件失败,服务器模板无效
- sql - 3 个表上的 DB2 全外连接
- r - 删除包含特定对象的多行
- java - 在 RDBMS 中保存 REST API JSON
- amazon-web-services - 使用 AWS Cloudformation 为 websocket API 网关创建自定义域名失败