计算列表中所有字符串长度总和的简单方法

Simple way to calculate the sum of all lengths of strings in a list

我有包含多个字符串的列表,例如:

['beth', 'Nissan', 'apple', 'three']

我正在寻找一种简短易行的方法(如果可能的话内联)来获取此列表中所有单个字符串的总和。这是我目前拥有的代码:

sum = 0
for string in list_of_strings:
    sum += len(string)

如果你想要总和使用:

result = sum([len(s) for s in list_of_strings])

如果您对累计总和感兴趣,请使用:

import numpy as np

result = np.cumsum([len(s) for s in list_of_strings])

这个怎么样

>>> strlist = ['beth', 'Nissan', 'apple', 'three']
>>> sum(len(x) for x in strlist)
20

或者你可以试试这个:

list_of_strings = ['beth', 'Nissan', 'apple', 'three']

s = sum(map(len, list_of_strings))

您可以使用 join 先连接字符串,然后立即计算长度:

list_of_strings = ['beth', 'Nissan', 'apple', 'three']
len(''.join(list_of_strings))