2013-08-06 61 views
2

代码:的Python 3:在列表中找到字符串,返回字符串和NONE

def find(string_list, search): 
    new_list = [] 
    for i in string_list: 
     if search in i: 
      new_list.append(i) 
    print(new_list) 

print(find(['she', 'sells', 'sea', 'shells', 'on', 'the', 'sea-shore'], 'he')) 

返回:

['she', 'shells', 'the'] 
None 
+2

默认返回值是'None'。从[print]中删除打印调用(find(...' –

+1

列表打印在函数中,而None则不是函数的结果) – zhangyangyu

回答

3

你不是return荷兰国际集团任何东西,所以该函数默认返回None 。此外,您还可以在一个更Python的方式做到这一点:

def find(string_list, search): 
    return [i for i in string_list if search in i] 

这就是所谓的列表理解,你可以阅读更多关于他们here

+0

至少链接到[list comprehensions](http:// docs.python.org/3/tutorial/datastructures.html#list-comprehensions) - 对于一个完全陌生的人来说,他们并不明显。 – thegrinner

+0

@thegrinner你是对的,我补充说。 – arshajii

+0

真棒,谢谢:) – thegrinner

2

这是溶液的函数的

def find(string_list, search): 
    new_list = [] 
    for i in string_list: 
     if search in i: 
      new_list.append(i) 
    return new_list 

print(find(['she', 'sells', 'sea', 'shells', 'on', 'the', 'sea-shore'], 'he')) 
+0

非常感谢。简单的开关就是这么做的! – user2656793

相关问题