Python: Sum string lengths

前端 未结 7 1328
暗喜
暗喜 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: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
    

提交回复
热议问题