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

2024-03-28 15:09:16 发布

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

我的一道作业题有困难。你知道吗

基本上,我要创建一个函数,使用for循环来计算列表中字符串中使用的字符数。我可以用len()得到字符串的长度,但是我只能得到其中一个字符串,而且我似乎无法以列表形式得到它。你知道吗

我的代码:

def method1(input1):

    total = 0

    a = []

    for word in input1:

        total = len(word)

        a = [total]

    return a

它返回[3]并输入['seven','one']

任何帮助都将不胜感激。我对Python很陌生。你知道吗


Tags: 函数字符串代码in列表forlendef
1条回答
网友
1楼 · 发布于 2024-03-28 15:09:16

这里有一种方法。列表“a”中有不同的字符串。您可以简单地遍历列表,计算每个字符串的len长度。你知道吗

def method1(input1):

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

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

您在这里所做的是接收输入并将其转换为列表。然后针对列表中的每个值,计算其长度。sum将这些长度相加,最后返回total。你知道吗

相关问题 更多 >