代码之家  ›  专栏  ›  技术社区  ›  Zaz Volodymyr Null

Python:字符串长度总和

  •  12
  • Zaz Volodymyr Null  · 技术社区  · 14 年前

    在Python中,有没有比使用循环更惯用的方法来求字符串长度的和?

    length = 0
    for string in strings:
        length += len(string)
    

    sum() ,但它只适用于整数:

    >>> sum('abc', 'de')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: sum() can't sum strings [use ''.join(seq) instead]
    
    7 回复  |  直到 11 年前
        1
  •  3
  •   Zaz Volodymyr Null    10 年前

    我知道这是一个老问题,但是我不得不注意到Python错误消息 你知道如何做到这一点:

    TypeError: sum() can't sum strings [use ''.join(seq) instead]
    

    所以:

    >>> strings = ['abc', 'de']
    >>> print len(''.join(strings))
    5
    
        2
  •  41
  •   liori    14 年前
    length = sum(len(s) for s in strings)
    
        3
  •  18
  •   Daenyth    14 年前

    我的第一个方法是 sum(map(len, strings)) . 另一种方法是使用一个列表理解或生成器表达式作为其他答案张贴。

        4
  •  6
  •   Raymond Hettinger    7 年前

    functional programming style 具有 map() sum() :

    >>> data = ['a', 'bc', 'def', 'ghij']
    >>> sum(map(len, data))
    10
    

    在python2中,使用 itertools.imap 地图 为了获得更好的内存性能:

    >>> from itertools import imap
    >>> data = ['a', 'bc', 'def', 'ghij']
    >>> sum(imap(len, data))
    10
    
        5
  •  2
  •   Tony Veijalainen    14 年前
    print(sum(len(mystr) for mystr in strings))
    
        6
  •  1
  •   sk8asd123    11 年前

    这是另一种使用运算符的方法。不确定这是否比公认的答案更容易阅读。

    import operator
    
    length = reduce(operator.add, map(len, strings))
    
    print length
    
        7
  •  -1
  •   shadab.tughlaq    10 年前

    再加上。。。

    从存储为字符串的列表中添加数字

    长度=总和(整数(s)表示s,单位为nos)