【问题标题】:How to make a list of the summed digits, in another list in Python? [duplicate]如何在 Python 的另一个列表中制作一个总和数字的列表? [复制]
【发布时间】:2019-05-09 18:42:08
【问题描述】:

有没有一种方法可以轻松地将列表中的数字转换为单个数字,例如

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 很陌生,所以我不确定我是否正确地这样做了

【问题讨论】:

  • print(list(item.count('1') for item in population))

标签: python python-3.x


【解决方案1】:

一种可能的方法是遍历population 列表并使用str.count('character') 计算每个“数字”字符串中的'1'

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

evaluation 将包含所需的计数:

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

【讨论】:

    【解决方案2】:

    如果您只处理零和一,那么@davedwards 是一个很好的解决方案。统计每个字符串中'1' 的实例。

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

    如果您需要解决方案对 0 和 1 以外的值更具可扩展性,您可以将每个数字转换为 int 并对整数求和。

    out = [sum(map(int, x)) for x in population]
    

    【讨论】:

      【解决方案3】:

      使用collections.Counter():

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

      一种功能方法是同时使用map()operator.itemgetter()

      >>> from collections import Counter
      >>> from operator import itemgetter
      >>> list(map(itemgetter('1'), map(Counter, population)))
      [2, 5, 3, 3]
      

      【讨论】:

        猜你喜欢
        • 2019-01-26
        • 2018-08-23
        • 2011-01-25
        • 2018-12-15
        • 2016-02-28
        • 2012-11-12
        • 1970-01-01
        • 1970-01-01
        • 2012-07-21
        相关资源
        最近更新 更多