首页 > 解决方案 > 按列表拆分字符串

问题描述

如何根据给定列表中的变量拆分字符串?
(我使用的是 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']

问题是一些变量以相同的字母开头。该程序不会查看# 符号,而是查看第一个字母。
在此先感谢您的帮助。

标签: pythonlist

解决方案


用于'|'.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 的建议使用


推荐阅读