如何使用PYTHON中的filter()函数在input_list中提取以“ s”开头和以“ p”结尾的名称列表?

时间:2020-04-27 16:06:06

标签: python-3.x startswith ends-with filterfunction

input_list =  ['soap','sharp','shy','silent','ship','summer','sheep']

使用s提取p中以input_list开头并以filter结尾({s和'p'均为小写))的名称列表功能。

输出应为:

['soap', 'sharp', 'ship', 'sheep']

6 个答案:

答案 0 :(得分:1)

这是如何轻松完成-

input_list =  ['soap','sharp','shy','silent','ship','summer','sheep']


def fil_func(name):
    if name[0]=='s' and name[-1]=='p':
        return True

correct_name = []
for i in input_list:
    name = list(filter(fil_func, input_list)) # list() is added because filter function returns a generator.
print(name)

答案 1 :(得分:1)

input_list = ['soap', 'sharp', 'shy', 'silent', 'ship', 'summer', 'sheep']

sp = list(filter(lambda x: x[0] == 's' and x[-1]=='p', input_list))

print(sp)

答案 2 :(得分:1)

sp = list(filter(lambda x: x.startswith("s") and x.endswith("p"), input_list))

print(sp)

这会给你正确的答案

答案 3 :(得分:0)

您在这里:

list(filter(lambda x: x.startswith("s") and x.endswith("p"), input_list))

答案 4 :(得分:0)

sp = list(filter(lambda x:x[0]=='s' and x[-1]=='p',input_list))


print(sp)

答案 5 :(得分:-1)

使用以下代码示例可以轻松完成:

input_list =  ['soap','sharp','shy','silent','ship','summer','sheep']

sp = list(filter(lambda x:x[0]=='s' and x[-1]=='p', input_list)) 

print(sp) 
相关问题