编写一个函数,将字符串列表和 returns 包含每个字符串长度的列表作为参数

Write a function that takes as a parameter a list of strings and returns a list containing the lengths of each of the strings

整个问题:编写一个函数,将一个字符串列表作为参数,return一个包含每个字符串长度的列表。也就是说,如果输入参数是["apple pie"、"brownies"、"chocolate"、"dulce de leche"、"eclairs"],你的函数应该return [9 , 8, 9, 14, 7].

我使用 "accumulator" 来处理这个程序,我会在其中累积列表。

我的程序:

def accumulating():
  List = []
  Strings = input("Please enter a list of strings: ")
  List = Strings.split(" ")
  return List

def length(n):
  r = []
  for i in n:
    r.append(len(n))
  return r

def main():
  y = accumulating()
  x = length(y)
  print(x)

main()
def accumulating(strings):
    return [len(i) for i in strings]

就是这样。

TigerhawkT3 有正确的答案,但如果您想更改代码,您可以这样做。在你的长度函数中,你不 return 字符串的长度,你只是打印它们。将其更改为:

def length(n):
    r = []
    for i in n:
        r.append(len(n))
    return r

def accumulating():
    list = []
    strings = input("Please enter a list of strings(seperated by a white space): ")
    list = strings.split(" ")
    return list

请在变量名中使用 cammelcase,以小写开头。这将避免混合变量和数据类型。 http://en.wikipedia.org/wiki/CamelCase

这是基本逻辑:

x = ["apple pie", "brownies","chocolate","dulce de leche","eclairs"]
y = []
for i in x:
    a = len(i)
    y.append(a)
print y

这与用户输入的逻辑相同:

b = raw_input("Please enter a list of strings(seperated by a comma): ")
x = []
x.append(b)
x = b.split(",")
y = []
for i in x:
    i = i.strip()
    a = len(i)
    y.append(a)
print y

我用x = b.split(",")所以用户输入可以用逗号分隔,然后i = i.strip()会去掉白色space所以a = len(i)会准确,白色 space 不会包含在 len 中。