首页 > 解决方案 > 我可以在列表理解中转换它吗?(或者让这段代码更快?)

问题描述

此代码获取 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)

老实说,我只需要让它更快,欢迎任何其他提示。

我无法导入任何库。

标签: python

解决方案


模拟您的解决方案的功能,在“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']]

推荐阅读