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

2024-09-29 01:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

Tags: of方法字符串代码inapple列表for
3条回答

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

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

这个怎么样

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

如果您想获得总和,请使用:

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])

相关问题 更多 >