-1

Is there a way to easily convert numbers in a list into single digits for example

population = ['10001','11111','11010','110001']

into ['1','0','0','0','1'] 

add each digit in each set and put it in another list like 
this

evaluation = [2,5,3,3] (adding up all the 1's up on the first list)

I'm very new to Python so I'm not sure if I'm doing this correctly

Mark Cruz
  • 21
  • 4

3 Answers3

4

One possible way is iterate over the population list and use str.count('character') to count the '1''s in each "number" string:

evaluation = list(item.count('1') for item in population)

evaluation will contain the desired counts:

>>> print(evaluation)
[2, 5, 3, 3]
2

If you are only dealing with zeros and ones, then @davedwards is a good solution. Count the instances of '1' in each string.

out = [x.count('1') for x in population]

If you need the solution to be more extensible to values other than 0 and 1, you can convert each digit to an int and sum the integers.

out = [sum(map(int, x)) for x in population]
James
  • 32,991
  • 4
  • 47
  • 70
0

Using collections.Counter():

>>> from collections import Counter
>>> population = ['10001','11111','11010','110001']
>>> [Counter(x).get('1', 0) for x in population]
[2, 5, 3, 3]

A functional aproach would be to also use map() and operator.itemgetter():

>>> from collections import Counter
>>> from operator import itemgetter
>>> list(map(itemgetter('1'), map(Counter, population)))
[2, 5, 3, 3]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75