实现逗号分隔字符串中连续相同值的分组计数格式化
Alright, let's tackle this problem where you need to group consecutive identical elements from a comma-separated string and format each group as [element] x[count]. Here's a straightforward way to do this using Python:
Example Input & Output
Input string:
"paid,paid,paid,paid,unpaid,paid,paid,paid,paid,unpaid,unpaid,unpaid,paid,paid,Pinterest,unpaid,Pinterest,unpaid,unpaid"
Expected output:"paid x4, unpaid x1, paid x4, unpaid x3, paid x2, Pinterest x1, unpaid x1, Pinterest x1, unpaid x2"
Solution Code
def group_consecutive_elements(input_str): # Split the input string into individual elements elements = input_str.split(',') if not elements: return "" result = [] # Start tracking the first element and its count current_element = elements[0] count = 1 # Iterate through the rest of the elements for elem in elements[1:]: if elem == current_element: count += 1 else: # Add the completed group to the result result.append(f"{current_element} x{count}") # Reset tracking to the new element current_element = elem count = 1 # Don't forget to add the final group after the loop ends result.append(f"{current_element} x{count}") # Join all groups into the final formatted string return ', '.join(result) # Test with your input data input_str = "paid,paid,paid,paid,unpaid,paid,paid,paid,paid,unpaid,unpaid,unpaid,paid,paid,Pinterest,unpaid,Pinterest,unpaid,unpaid" print(group_consecutive_elements(input_str))
How It Works
- Split the Input: We first break the comma-separated string into a list of individual elements to iterate over.
- Track Consecutive Elements: We keep track of the current element we're counting and how many times it's appeared consecutively.
- Build Groups: As we loop through elements, we increment the count if the element matches the current tracked one. When we hit a new element, we format the existing group and add it to our result list, then reset our tracker.
- Final Group Handling: After the loop finishes, we add the last remaining group (since the loop won't trigger the group addition for the final set of elements).
- Format Output: Finally, we join all the formatted groups back into a single comma-separated string.
This logic is easy to adapt to other languages too—just replicate the "track current element + count consecutive matches" pattern!
内容的提问来源于stack exchange,提问作者Hound
相关产品推荐
相关产品推荐

