Search code examples
pythonstringcounter

How to convert a list of counters into a list with items and values combined in python?


I have

x = [('a', 1), ('ab', 1), ('abc', 1), ('abcd', 1), ('b', 1), ('bc', 1), ('bcd', 1), ('c', 1), ('cd', 1), ('d', 1)]

I want to convert each of the elements in x such that:

('a',1) --> 'a1';

('ab', 1) --> 'ab1';

('abc', 1) --> 'abc1';

For your reference:

This is how I got x: x = list(Counter(words).items())


Solution

  • Assuming you are using Python 3.6+, you can use a list comprehension and an f-string:

    x = [('a', 1), ('ab', 1), ('abc', 1), ('abcd', 1), ('b', 1), ('bc', 1), ('bcd', 1), ('c', 1), ('cd', 1), ('d', 1)]
    output = [f'{first}{second}' for first, second in x]
    

    If you are using a previous version:

    output = ['{first}{second}'.format(first=first, second=second) for first, second in x]