首页 > 解决方案 > 如何将列表中的一部分数字组合在一起Python

问题描述

我目前正在开发一个程序,在该程序中,我必须将字符串作为输入,然后反转该字符串中的所有数字,使所有其他字符保持不变。我设法做到了,但是似乎我必须一次反转数字部分,而不是反转每个数字。我不确定如何用我的解决方案做到这一点。我宁愿不使用任何库。

例如:

对于输入 abc123abc456abc7891

我的结果:abc198abc765abc4321

目标结果:abc321abc654abc1987

这是我所拥有的:

#Fucntion just reverses the numbers that getn gives to it
def reverse(t):
    t = t[::-1]
    return t

def getn(w):
    w = list(w)
    Li = []
#Going through each character of w(the inputted string) and adding any numbers to the list Li
    for i in w:
        if i.isdigit():
            Li.append(i)
#Turn Li back into a string so I can then reverse it using the above function
#after reversing, I turn it back into a list
    Li = ''.join(Li)
    Li = reverse(Li)
    Li = list(Li)
#I use t only for the purpose of the for loop below,
#to get the len of the string,
#a is used to increment the position in Li
    t = ''.join(w)
    a = 0
#This goes through each position of the string again,
#and replaces each of the original numbers with the reversed sequence
    for i in range(0,len(t)):
        if w[i].isdigit():
            w[i] = Li[a]
            a+=1
#Turn w back into a string to print
    w = ''.join(w)
    print('New String:\n'+w)

x = input('Enter String:\n')
getn(x)

标签: pythonpython-3.xfunction

解决方案


解决方案概述:

  • 将字符串分解为子字符串列表。每个子字符串由数字和非数字之间的划分定义。您在此阶段结束时的结果应该是["abc", "123", "abc", "456", "abc", "7891"]
  • 浏览此列表;用它的反向替换每个数字字符串。
  • join此列表为单个字符串。

最后一步很简单''.join(substring_list)

中间步骤包含在您已经在做的事情中。

第一步并非微不足道,但在您原始帖子中的编码能力范围内。

你能从这里拿走吗?


更新

这是根据需要将字符串分成组的逻辑。检查每个字符的“数字”。如果它与前一个字符不同,那么您必须开始一个新的子字符串。

instr = "abc123abc456abc7891"

substr = ""
sub_list = []
prev_digit = instr[0].isdigit()

for char in instr:
    # if the character's digit-ness is different from the last one,
    #    then "tie off" the current substring and start a new one.
    this_digit = char.isdigit()
    if this_digit != prev_digit:
        sub_list.append(substr)
        substr = ""
        prev_digit = this_digit

    substr += char

# Add the last substr to the list
sub_list.append(substr)

print(sub_list)

输出:

['abc', '123', 'abc', '456', 'abc', '7891']

推荐阅读