简体   繁体   English

计算列表中字符串中的字符,Python

[英]Counting the characters in strings within a list, Python

I am having difficulty with one of my homework questions. 我有一个家庭作业问题遇到困难。

Basically, I am to create a function using a for loop to count the characters used in strings which are inside of a list. 基本上,我要使用for循环创建一个函数,以计算列表内部字符串中使用的字符。 I am able to get the length of the strings with len(), but I can only get one of the strings and I can't seem to get it in list form. 我可以使用len()获得字符串的长度,但是我只能获得其中一个字符串,而且似乎无法以列表形式获得它。

My Code: 我的代码:

def method1(input1):

    total = 0

    a = []

    for word in input1:

        total = len(word)

        a = [total]

    return a

This returns [3] with the input ['seven', 'one'] 返回[3],输入为['seven','one']

Any help would be appreciated. 任何帮助,将不胜感激。 I am very new to Python. 我对Python很陌生。

Well here is one way of doing it. 好吧,这是一种实现方法。 You have list "a" with different strings inside of them. 您在列表“ a”中包含不同的字符串。 You can simply iterate through the list counting the len gth of each string. 您可以通过列表计数简单地重复len每个字符串的GTH。

def method1(input1):

    l = list(input1)
    total = sum(len(i) for i in l)
    return int(total)

print(method1(["hello", "bye"]))

What you are doing here is receiving an input and converting it to a list. 您在这里所做的就是接收输入并将其转换为列表。 Then for each value inside of the list, you are calculating it's length. 然后,对于列表中的每个值,您正在计算其长度。 The sum adds up those lengths and finally, you return total . sum将这些长度加起来,最后返回total

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM