整个问题:编写一个函数,该函数将字符串列表作为参数,并返回包含每个字符串长度的列表。也就是说,如果输入参数为[“ apple pie”,“ brownies”,“ chocolate”,“ dulce de leche”,“ eclairs”],则函数应返回[9、8、9、14、7]。
我使用一个“累加器”来处理该程序,在那里我会累加列表。
我的程序:
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()
TigerhawkT3有正确的答案,但是如果您想更改代码,则可以执行此操作。在您的length函数中,您不返回字符串的长度,而只是打印它们。更改为:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句