Skip to main content
 首页 » 编程设计

python之如何将字符串拆分为奇数序列

2025年05月04日19Leo_wl

我正在尝试找到一种将数字拆分为奇数序列列表的方法:

num = "57483795478973" 
 
for digit in num: 
    if int(digit)%2==0: 
        list_a = str.split(num,digit) 
 
print (list_a) 

但我得到的结果是

['574', '379547', '973'] 

其中包括偶数,我不明白我做错了什么。

请您参考如下方法:

这是一个使用 re 的解决方案模块:

>>> import re 
>>> re.split('[02468]', '57483795478973') 
['57', '', '3795', '7', '973'] 

在这种情况下,第一个参数实际上是一个分隔符列表 - 在您的例子中是偶数。如果您想跳过空结果:

>>>[r for r in re.split('[02468]', '57483795478973') if r] 
['57', '3795', '7', '973'] 

这是一种手动计算的方法,使用 generator :

def splitToOddSeqs(numbers): 
    seq = "" 
    for n in numbers: 
        if n not in "02468": 
            seq += n      # as long as we have odd numbers, we accumulate 
        else: 
            if seq: 
                yield seq # we've found an even number - return one sequence 
                seq = "" 
 
    if seq: 
        yield seq         # return last one (when input ends with odd digit) 

示例用法:

>>> list(splitToOddSeqs('57483795478973')) 
['57', '3795', '7', '973']