Inf*_*ity -3 python for-loop if-statement startswith python-2.7
我想在数组列表中运行for循环并打印出任何带有"monkey"字样的内容.我在下面编写了以下代码,但它给了我一个错误.我不太确定我做错了什么.任何帮助都会很棒,谢谢.
a= "monkeybanana"
b= "monkeyape"
c= "apple"
list= [a, b, c]
print "The words that start with monkey are:"
for k in words:
if list.startswith('monkey'):
print list
Run Code Online (Sandbox Code Playgroud)
你需要改变它
a= "monkeybanana"
b= "monkeyape"
c= "apple"
lst = [a, b, c]
print "The words that start with monkey are:"
for k in lst:
if k.startswith('monkey'):
print k
Run Code Online (Sandbox Code Playgroud)
基本上你正在迭代words,但该名称不存在.
然后用
if list.startswith('monkey'):
Run Code Online (Sandbox Code Playgroud)
代码检查单词列表的开头monkey,而不是列表的元素(k)
最后
print list
Run Code Online (Sandbox Code Playgroud)
打印整个列表,而不是它的当前元素
注意:整个算法可以使用过滤器减少到一行
print filter(lambda x: x.startswith('monkey'), lst)
Run Code Online (Sandbox Code Playgroud)
注意2:避免使用名称python使用的命名变量.如果您使用list变量名称,它将影响内置list函数,您将无法使用它.