1

Note: Please make sure this is not duplicate, i am trying to find one liner way.

I am trying to turn string filled with ascii letters to string filled with occurrence of ascii letters.

For example: string1 = 'abc'.

To turn this into string filled with occurrence of ascii letters, i would simply use one line command:

string2 = [string1.count(l) for l in string1]

And this would output:

[1, 1, 1]


But if i had multiple repeated characters in string1, it would look different.

For example: string1 = 'aaabbbccc'

And transforming it:

string2 = [string1.count(l) for l in string1]

And output would be:

[3, 3, 3, 3, 3, 3, 3, 3, 3]


So as you see, character occurrences are repeated, and i don't know how can i make a generator that prints single occurrence of single letter only once.

So for example:

Instead of:

[3, 3, 3, 3, 3, 3, 3, 3, 3]

Is there a way to output this with single line generator?

[3, 3, 3]

ShellRox
  • 2,532
  • 6
  • 42
  • 90

3 Answers3

4

You can do it in one line with an OrderedCounter.

>>> from collections import Counter, OrderedDict
>>> class OrderedCounter(Counter, OrderedDict): 
...     pass
...
>>> OrderedCounter('aaabbbccc').values()
[3, 3, 3]
wim
  • 338,267
  • 99
  • 616
  • 750
4

Use collections.Counter:

>>> from collections import Counter
>>> Counter('aaabbbccc')
Counter({'a': 3, 'b': 3, 'c': 3})

You can get the counts as a sorted list easily by iterating the counter with string.ascii_lowercase:

>>> import string
>>> c = Counter('aaabbbccc')
>>> [c[l] for l in string.ascii_lowercase]
[3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Uriel
  • 15,579
  • 6
  • 25
  • 46
0

Use set:

>>> [string1.count(l) for l in set(string1)]
[3, 3, 3]

Set turns a string into a set of distinct characters: e.g. aabc and abbc but also acb will turn into {'a', 'b', 'c'}

This is the output you looked for, but you would not know which 3 goes to which character, so in the end you'd be better off using the Counter methods suggested

hansaplast
  • 11,007
  • 2
  • 61
  • 75
  • Hello, do you know how could this output also be turned into a string easily? without brackets, thanks! – ShellRox Feb 06 '17 at 16:58