【问题标题】:Using startswith in lambda expression and filter function with Python在 lambda 表达式中使用 startswith 和 Python 中的过滤器函数
【发布时间】:2021-05-14 18:39:51
【问题描述】:

我正在尝试查找以字符“s”开头的单词。我有一个字符串列表(seq)要检查。

seq = ['soup','dog','salad','cat','great']

sseq = " ".join(seq)

filtered = lambda x: True if sseq.startswith('s') else False

filtered_list = filter(filtered, seq)

print('Words are:')
for a in filtered_list:
    print(a)

输出是:

Words are:
soup
dog
salad
cat
great

我在哪里看到整个列表。如何使用 lambda 和 filter() 方法返回以 "s" 开头的单词?谢谢

【问题讨论】:

  • 为什么不使用简单的列表推导?毕竟,Python 就是简单地做事。 :-)
  • [word for word in seq if word.lower().startswith('s')]
  • 为什么filtered 忽略它的论点?
  • 你为什么在函数中使用sseq,而不是x,参数?你为什么要创建sseq
  • 另外,顺便说一句,不要将 lambda 表达式分配给名称。如果您要这样做,只需使用完整的函数定义

标签: python python-3.x list lambda filter


【解决方案1】:

您的过滤器 lambda 始终只检查您加入的单词的开头,而不是您传入的字母。

filtered = lambda x: x.startswith('s')

【讨论】:

    【解决方案2】:

    试试这个。

    seq = ['soup','dog','salad','cat','great']
    result = list(filter(lambda x: (x[0] == 's'), seq)) 
    print(result)
    

    seq = ['soup','dog','salad','cat','great']
    result = list(filter(lambda x: x.startswith('s'),seq))
    print(result)
    

    两个输出

    ['soup', 'salad']
    

    【讨论】:

      【解决方案3】:

      如果您可以不使用filter,这是另一种优雅的方法:

      filtered_list = [x for x in seq if x.startswith('s')]
      print('Words are: '+ " , ".join(filtered_list))
      

      输出:

      Words are: soup , salad
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-20
        • 1970-01-01
        相关资源
        最近更新 更多