How to make a list of the summed digits, in another list in Python?
本问题已经有最佳答案,请猛点这里访问。
有没有一种方法可以很容易地将列表中的数字转换为单个数字,例如
1 2 3 4 5 6 7 8 | 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) |
我对python很陌生,所以我不确定我做的是否正确
一种可能的方法是迭代
1 | evaluation = list(item.count('1') for item in population) |
1 2 | >>> print(evaluation) [2, 5, 3, 3] |
如果您只处理0和1,那么@davidwards是一个很好的解决方案。计算每个字符串中
1 | out = [x.count('1') for x in population] |
如果您需要对0和1以外的值进行更大的扩展,可以将每个数字转换为int并求和整数。
1 | out = [sum(map(int, x)) for x in population] |
使用
1 2 3 4 | >>> from collections import Counter >>> population = ['10001','11111','11010','110001'] >>> [Counter(x).get('1', 0) for x in population] [2, 5, 3, 3] |
一个功能性的方案是也使用
1 2 3 4 | >>> from collections import Counter >>> from operator import itemgetter >>> list(map(itemgetter('1'), map(Counter, population))) [2, 5, 3, 3] |