Skip to content

i have a large list like this ['z','z','z','z','e','e','e','z','z'] i want to print '4z3e2z' help please #31

Answered by Tanu-N-Prabhu
vkp3803 asked this question in Q&A
Discussion options

You must be logged in to vote

Try this ;)

def compress_list(data):
    if not data:
        return ""

    result = []
    count = 1

    for i in range(1, len(data)):
        if data[i] == data[i - 1]:
            count += 1
        else:
            result.append(f"{count}{data[i - 1]}")
            count = 1
    # Append the last group
    result.append(f"{count}{data[-1]}")
    
    return ''.join(result)

# Example usage
data = ['z','z','z','z','e','e','e','z','z']
print(compress_list(data))  # Output: 4z3e2z

Explanation:

  • Loop through the list and keep a count of how many times the current character repeats.
  • When the current character changes, store the count and character in the result, and reset the count.
  • Fi…

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by Tanu-N-Prabhu
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants