【问题标题】:Python 3: Finding string in a list, returns the strings and NONE [duplicate]Python 3:在列表中查找字符串,返回字符串和 NONE [重复]
【发布时间】:2013-08-06 12:40:29
【问题描述】:

代码:

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

【问题讨论】:

  • 函数的默认返回值为None。从print(find(...删除打印调用
  • 列表在函数中打印。而 None 是函数的结果。

标签: python string list python-3.x


【解决方案1】:

你不是returning 任何东西,所以函数默认返回None。此外,您可以以更 Pythonic 的方式执行此操作:

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

这称为列表理解,您可以阅读更多关于它们的信息here

【讨论】:

  • 至少链接到list comprehensions 上的解释 - 对于完全不熟悉 Python 的人来说,它们并不明显。
  • @thegrinner 你说得对,我补充了。
  • 谢谢。我欣赏更高效的版本。
  • @user2656793 很高兴我能帮上忙。别忘了accept an answer
【解决方案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'))

【讨论】:

  • 非常感谢。简单的开关就可以了! :)
猜你喜欢
  • 2019-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多