2016-01-13 195 views
-4

我想在数组列表中运行一个for循环,并打印出其中包含单词'monkey'的任何内容。我在下面写了下面的代码,但它给了我一个错误。我不太确定我做错了什么。任何帮助将是伟大的,谢谢。Python startswith()循环和if语句

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 
+0

与尝试'如果k.startswith(‘猴子’):'和'打印k' – Delgan

+0

如果k.startswith('monkey'):? –

+1

话是从哪里来的? –

回答

4

你需要将其更改为

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 

基本上你是迭代上words,但名称不存在。

然后用

if list.startswith('monkey'): 

代码检查单词列表开始与monkey,列表(k

最后

print list 

打印整个列表的不是元素,不是它的当前元素

注:整个算法可以用filter

print filter(lambda x: x.startswith('monkey'), lst) 

注2减少到一条线:避免命名变量,名Python使用了。如果使用list作为变量名称,它将遮蔽内置的list功能,您将无法使用它。

1

您正在访问不同的数据。尝试:

a= "monkeybanana" 
b= "monkeyape" 
c= "apple" 
list= [a, b, c] 


print "The words that start with monkey are:" 

for k in list: 
    if k.startswith('monkey'): 
     print k 
0

有Python打印错误,你应该检查那些!

你想要做的是检查列表中的每个单词,看它里面是否有'猴'。 你写的(类型)转换为:对于列表中的每个单词,检查列表以查看它是否以'monkey'开头。

当然,如果你想打印有'猴子'的单词,你必须打印这个单词(print k在你的场景中,因为这是你目前正在阅读的单词) ,而不是名单本身。

要尽快得到答案:

如果你想看看“猴子”是在一个字(因为这个问题说的)在列表中:

a = "monkeybanana" 
b = "monkeyape" 
c = "apple" 
list = [a, b, c] 


print "The words that start with monkey are:" 

for k in list: 
    if 'monkey' in k: 
     print k 

如果你想看看“猴子”是在一个单词的开头(如标题和代码说吧)在列表中:

a = "monkeybanana" 
b = "monkeyape" 
c = "apple" 
list = [a, b, c] 


print "The words that start with monkey are:" 

for k in list: 
    if k.startswith('monkey'): 
     print k