簡體   English   中英

如何將列表中的數字部分分組在一起

[英]How to group a section of numbers in a list together 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)

以下內容並不是特別優雅,但從概念上講相當簡單,使用itertools groupby將字符串分成數字或非數字組(這是Python 3.7,我認為它應可在任何Python 3.x上使用,但除3.7之外未測試):

from itertools import groupby

def getn(s):
    sections = groupby(s, key=lambda char: char.isdigit())
    result = []
    for isdig, chars in sections:
        if isdig:
            result += list(reversed(list(chars)))
        else:
            result += list(chars)
    return "".join(result)

input = "abc123abc456abc7891"
print(getn(input))

解決方案概述:

  • 將字符串分成子字符串列表。 每個子字符串由數字和非數字之間的分界來定義。 在此階段結束時,您的結果應為["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']

這是一個基於@prune建議的工作代碼。

def type_changed(s1,s2):
    if s1.isdigit() != s2.isdigit():
        return True

def get_subs(s):
    sub_strings = list()
    i = 0
    start = i
    while i < len(s):
        if i == len(s)-1:
            sub_strings.append(s[start:i+1])
            break
        if type_changed(s[i], s[i+1]):
            sub_strings.append(s[start:i+1])
            start = i+1
        i +=1
    return sub_strings

def reverse(subs):
    for i, sub in enumerate(subs):
        if sub.isdigit():
            subs[i] = subs[i][::-1]
    return ''.join(subs)


test_strings = [
    'abc123abc456abc7891b',
    'abc123abc456abc7891',
    'abc123abc456abc7891abc',
    'a1b2c3d4e5f6',
    'a1b2c3d4e5f6g',
    '1234',
    'abcd',
    '1',
    'a'
]

for item in test_strings:
    print(item)
    print(reverse(get_subs(item)))
    print

想法是將數字和字母分成子字符串部分。 遍歷每個部分,僅反轉整數部分。 然后將這些部分連接到一個字符串中。

def getn(w):
   ans = []
   section = ''

   if w[0].isdigit():
       last = 'digit'
   else:
       last = 'letter'

   for char in w:
       if char.isdigit():
           if last == 'letter':
               ans.append(section)
               section = ''
               last = 'digit'
           section += char
       else:
           if last == 'digit':
               ans.append(section)
               section = ''
               last = 'letter'
           section += char
   ans.append(section)

   for index, section in enumerate(ans):
       if section.isdigit():
           ans[index] = section[::-1]
   return ''.join(ans)

string = 'abc123abc456abc7891'
print(getn(string))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM