![](/img/trans.png)
[英]Python: Simple Question regarding counting characters on a list of strings
[英]Counting the characters in strings within a list, Python
我有一個家庭作業問題遇到困難。
基本上,我要使用for循環創建一個函數,以計算列表內部字符串中使用的字符。 我可以使用len()獲得字符串的長度,但是我只能獲得其中一個字符串,而且似乎無法以列表形式獲得它。
我的代碼:
def method1(input1):
total = 0
a = []
for word in input1:
total = len(word)
a = [total]
return a
返回[3],輸入為['seven','one']
任何幫助,將不勝感激。 我對Python很陌生。
好吧,這是一種實現方法。 您在列表“ a”中包含不同的字符串。 您可以通過列表計數簡單地重復len
每個字符串的GTH。
def method1(input1):
l = list(input1)
total = sum(len(i) for i in l)
return int(total)
print(method1(["hello", "bye"]))
您在這里所做的就是接收輸入並將其轉換為列表。 然后,對於列表中的每個值,您正在計算其長度。 sum
將這些長度加起來,最后返回total
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.