Python字符串转列表:符合条件时合并元素
Hey there! As someone new to Python, this problem might seem tricky at first, but it's actually a great chance to practice basic string and list manipulation. Let's walk through a straightforward solution that does exactly what you need.
The Core Idea
We'll iterate through each character in your input string. Whenever we hit a modifier (from your modifiers_list), we'll append it to the last character group in our result list. For regular characters, we'll add them as new entries in the list.
Working Code Example
input_text = "gʷʰsoʷngʲʷʰos" modifiers_list = ["ʷ", "ʰ", "ʲ"] output_list = [] for char in input_text: # Check if current character is a modifier and we have existing entries if char in modifiers_list and output_list: # Merge modifier with the last element in the list output_list[-1] += char else: # Add regular character as a new list item output_list.append(char) print(output_list) # Output: ['gʷʰ', 's', 'oʷ', 'n', 'gʲʷʰ', 'o', 's']
Breakdown of the Code
- Initialization: We start with an empty
output_listto build our result. - Loop Through Characters: For every character in
input_text:- If the character is a modifier and our result list isn't empty (to avoid errors if the string starts with a modifier), we add it to the end of the last item in the list.
- If it's a regular character, we add it as a new item to the list.
Bonus: Making It More Robust
If you're worried about edge cases (like the input string starting with a modifier), the code above already handles that by checking if output_list is non-empty before merging. If a modifier comes first, it'll just be added as its own list item instead of causing an error.
内容的提问来源于stack exchange,提问作者Lindeby

