【问题标题】:Return one or more values from a list if they appear in a substring如果它们出现在子字符串中,则从列表中返回一个或多个值
【发布时间】:2022-01-19 19:23:58
【问题描述】:

我有一个列表和一个字符串:

lst = ['rock','paper','scissor','green apple', 'red apple']

我想创建一个函数,如果它们在文本中显示为子字符串,则从列表中返回一串项目

例如:

lst = ['rock','paper','scissor','green apple', 'red apple']
def my_func(string):
        .
        .
        .
    return print(new_string)

#------------

string1 = 'we like rock and green apples' 
string2 = 'i wrote on paper'
string3 = 'we played rock, paper, scissors, and had apples'

my_func(string1)
my_func(string2)
my_func(string3)

rock, green apples
paper 
rock, paper, scissor

【问题讨论】:

    标签: python list function substring


    【解决方案1】:

    给你!

    lst = ['rock','paper','scissor','green apple', 'red apple']
    def my_func(string):
        new_string = ''
        for i in lst:
            if i in string:
                new_string += i + ', '
        return print(new_string)
    
    string1 = 'we like rock and green apples'
    string2 = 'i wrote on paper'
    string3 = 'we played rock, paper, scissors, and had apples'
    
    my_func(string1)
    my_func(string2)
    my_func(string3)
    

    【讨论】:

    • 谢谢 :) 我会尽快接受答案
    • 更改为 new_string += ('' if new_string == '' else ', ') + i 以删除悬空逗号
    猜你喜欢
    • 2021-07-31
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 2016-05-16
    相关资源
    最近更新 更多