cách tiếp cận khác có thể là -
import re
input_string = 'A3G3A'
alphabets = re.findall('[A-Z]', input_string) # List of all alphabets - ['A', 'G', 'A']
digits = re.findall('[0-9]+', input_string) # List of all numbers - ['3', '3']
final_output = "".join([alphabets[i]*int(digits[i]) for i in range(0, len(alphabets)-1)]) + alphabets[-1]
# This expression repeats each letter by the number next to it (Except for the last letter), joins the list of strings into a single string, and appends the last character
# final_output - 'AAAGGGA'
Giải thích -
In [31]: alphabets # List of alphabets in the string
Out[31]: ['A', 'G', 'A']
In [32]: digits # List of numbers in the string (Including numbers more than one digit)
Out[32]: ['3', '3']
In [33]: list_of_strings = [alphabets[i]*int(digits[i]) for i in range(0, len(alphabets)-1)] # List of strings after repetition
In [34]: list_of_strings
Out[34]: ['AAA', 'GGG']
In [35]: joined_string = "".join(list_of_strings) # Joined list of strings
In [36]: joined_string
Out[36]: 'AAAGGG'
In [38]: final_output = joined_string + input_string[-1] # Append last character of the string
In [39]: final_output
Out[39]: 'AAAGGGA'
[itertools.groupby] (https://docs.python.org/3/library/itertools .html # itertools.groupby) - nó sẽ tạo ra các trình lặp có chứa {A, 10, G, 3, ABC}? dựa trên lật đúng/sai của isdigit? –
@PatrickArtner, có nhưng nó cũng sẽ bao gồm kết quả của 'isdigit()' cùng với các trình vòng lặp để bạn cũng biết những gì bạn đang xem! Về mặt khái niệm, một cái gì đó như: '[(Sai, ['A']), (Đúng, ['1', '0']), (Sai, ['G']), (Đúng, ['3']) , (False, ['A', 'B', 'C'])] ' – cdlane
gọn gàng, thx để giải thích –