简体   繁体   English

如何在函数内使用for循环返回元素?

[英]How to return elements using for loop within a function?

Below is the given list of strings from which I am trying to find the strings which contains the substring.下面是给定的字符串列表,我试图从中找到包含子字符串的字符串。 Output is obtained perfectly without using functions.无需使用函数即可完美获得输出。 However when function is used, it does return only 1 substring and not the list of strings containing the substring.但是,当使用函数时,它只返回 1 个子字符串,而不是包含子字符串的字符串列表。

L = ['dog', 'dodge', 'cat', 'cattle']

sub_string = str(input("Enter the substring: "))

for i in range(len(L)):
    v = L[i].find(sub_string, 0,100)
    if v >= 0:
        print(L[i])           #returns all the strings containing the substring very well.

def String_find(sub_string):
    for i in range(len(L)):
        if sub_string in L[i]:         
            return L[i]        #returns only 'dog' or 'cat' if substring is entered whereas 
                               #'dog','dodge' 
                               #or 'cat','cattle' is expected.

Total = String_find(sub_string)
#Output is obtained perfectly without using functions however when function is used it does return         
#only 1 substring and not the list of strings containing the substring.

You maybe want to do this:你可能想要这样做:

def string_find(sub):
    return [item for item in L if sub in item]

items = string_find(sub_string)
print(items)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM