python - 我可以在列表理解中转换它吗?(或者让这段代码更快?)
问题描述
此代码获取 a 和 b 的列表并创建 a 和 b 的序列。在每个序列中可以是 a 的 x 个数字和 b 的 x 个数字,但不可能有一个字母来划分另一个(允许使用 aabb,但不允许使用 aaba)。是否可以在列表理解中转换它?
list_of_strings=["abaababbaabaaabbabbab","abbabbbabbbaa"]
final_list=[]
for elt in list_of_strings:
final_list.append([])
is_a=0
for idx in range(1,len(elt)):
if elt[idx] < elt[idx-1]: #try to find the index where a 'b' is followed by a 'a'
final_list[-1].append(elt[is_a:idx]) #add the segment on the sublist of final_list. idx (correspond to a new 'a') is not include
is_a=idx #the begin of next segment is the index of the new 'a'
final_list[-1].append(elt[is_a:idx+1]) #finish with the lasts 'a' on the string
print(final_list)
老实说,我只需要让它更快,欢迎任何其他提示。
我无法导入任何库。
解决方案
模拟您的解决方案的功能,在“b”更改为“a”时拆分:
>>> [s.replace('ba', 'b a').split() for s in list_of_strings]
[['ab', 'aab', 'abb', 'aab', 'aaabb', 'abb', 'ab'],
['abb', 'abbb', 'abbb', 'aa']]
推荐阅读
- javascript - Javascript JSON DOM 选择器:如何告诉 JS 根据 html 选择器从 JSON 中过滤一些卡片?
- ios - 无法使用协议/委托将值从子 VC 传递到父 VC
- python - 剥离列表返回空白值
- scala - 如何在 Azure Web App 中部署 Play Framework API App
- javascript - 是否可以仅在单击按钮而不使用使用css或scss的javascript时触发动画
- php - 如何在没有 Api 的情况下通过 PHP 获取亚马逊产品数据
- java - Char 数组值不保存 JAVA 中的用户输入值
- colors - 如何使用 python 在 plotly 中更改图例/标记颜色?
- css - HTML + CSS 如何将按钮作为文本框内的图像
- java - Java Print 格式化十进制