2024-09-29 01:29:38 发布
网友
我有包含多个字符串的列表,如:
['beth', 'Nissan', 'apple', 'three']
我正在寻找一种简单快捷的方法(如果可能的话,可以内联)来获取列表中所有单个字符串的总和。这是我目前拥有的代码:
sum = 0 for string in list_of_strings: sum += len(string)
可以使用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])
可以使用join先连接字符串,然后立即计算长度:
这个怎么样
如果您想获得总和,请使用:
如果您对累计总和感兴趣,请使用:
相关问题 更多 >
编程相关推荐