我有包含多個字串的串列,例如:
['beth', 'Nissan', 'apple', 'three']/code>
我正在尋找一個簡短而簡單的方法(如果可能的話,可以行內)來獲得這個串列中所有單獨字串的總和。這是我目前擁有的代碼:
sum = 0
for string in list_of_strings:
sum = len(string)
uj5u.com熱心網友回復:
這個怎么樣
>>> strlist = ['beth', 'Nissan', 'apple', 'three']
>>> sum(len(x) forx in strlist)
20
uj5u.com熱心網友回復:
如果你想得到總和,請使用:
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] )
uj5u.com熱心網友回復:
另外,你可以嘗試這樣做:
list_of_strings = ['beth'/span>, 'Nissan', 'apple', 'three']
s = sum(map(len, list_of_strings)
uj5u.com熱心網友回復:
你可以使用join來首先連接字串,然后一次性計算長度:
你可以使用join來首先連接字串,然后一次性計算長度。
list_of_strings = ['beth'/span>, 'Nissan', 'apple', 'three']
len('.join(list_of_strings))
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/332543.html
標籤:
