我在使代码返回从输入中创建的新列表时遇到麻烦。
def beagle(list):
bg=[] #this is the list for beagles
new=list.split(",")
return new
for i in new:
if "beagle" in new:
bg.append("beagle")
return bg
else:
return bg
return len(gr)
print(beagle("cat, dog, beagle, golden retriever, beagle"))
即使我的if和else语句中都有“ return bg”,输出也不返回任何内容。
答案 0 :(得分:0)
如果我明白这一点,则还需要删除空格(最好不要调用列表list
):
[x.strip() for x in my_list.split(',')]
不要太早返回,也要在列表后附加i
def beagle(my_list):
bg=[] #this is the list for beagles
new=[x.strip() for x in my_list.split(',')]
# return new # <-- remove early return
for i in new:
if "beagle" in new:
bg.append(i)
# else:
# return bg
return bg
结果是:
print(beagle("cat, dog, beagle, golden retriever, beagle"))
#=> ['cat', 'dog', 'beagle', 'golden retriever', 'beagle']
print(beagle("cat, dog, golden retriever"))
#=> []
if "beagle" in new:
for i in new:
bg.append(i)
答案 1 :(得分:0)
尝试一下:
#1 删除此return语句,否则将不执行functuin的以下代码
#2 在" "
(逗号)后添加","
(空格)。如果将字符串列表("cat, dog, beagle, golden retriever, beagle"
)除以","
,则得到["cat", " dog", " beagle", " golden retriever", " beagle"]
,因此可以改为", "
。您将获得["cat", "dog", "beagle", "golden retriever", "beagle"]
def beagle(list):
bg=[] #this is the list for beagles
new=list.split(", ") # <--- #2
# return new <--- #1
for i in new:
if "beagle" in new:
bg.append("beagle")
return bg
else:
return bg
return len(bg)
print(beagle("cat, dog, beagle, golden retriever, beagle"))