Python: Sum string lengths

前端 未结 7 1316
暗喜
暗喜 2020-12-06 17:17

Is there a more idiomatic way to sum string lengths in Python than by using a loop?

length = 0
for string in strings:
    length += len(string)
相关标签:
7条回答
  • 2020-12-06 17:27
    length = sum(len(s) for s in strings)
    
    0 讨论(0)
  • 2020-12-06 17:28

    Just to add upon ...

    Adding numbers from a list stored as a string

    nos = ['1','14','34']

    length = sum(int(s) for s in nos)

    0 讨论(0)
  • 2020-12-06 17:31

    The shortest and fastest way is apply a functional programming style with map() and sum():

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

    In Python 2, use itertools.imap instead of map for better memory performance:

    >>> from itertools import imap
    >>> data = ['a', 'bc', 'def', 'ghij']
    >>> sum(imap(len, data))
    10
    
    0 讨论(0)
  • 2020-12-06 17:31
    print(sum(len(mystr) for mystr in strings))
    
    0 讨论(0)
  • 2020-12-06 17:37

    My first way to do it would be sum(map(len, strings)). Another way is to use a list comprehension or generator expression as the other answers have posted.

    0 讨论(0)
  • 2020-12-06 17:42

    I know this is an old question, but I can't help noting that the Python error message tells you how to do this:

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

    So:

    >>> strings = ['abc', 'de']
    >>> print len(''.join(strings))
    5
    
    0 讨论(0)
提交回复
热议问题