返回子字符串的列表索引的函数

我正在努力创建一个搜索列表的函数,以查看其中包含的任何字符串是否为同一列表中其他字符串的substrings。如果找到substring,则应返回index号;如果找不到,则应返回False

例如。

lst1 = ["red","yellow","green","yellowhammer"]
lst2 = ["red","green"]

在此示例中,lst1将返回值1,因为yellowsubstring的{​​{1}},而yellowhammer将返回值{{ 1}},因为没有lst2

我尝试了以下

False

但是,这不起作用,因为它总是会找到自己,因此即使没有substrings,它也会返回一个值,即使它应该返回templst = lst1 for i in templst: if i in lst1: return i else: return False

cjzmly123 回答:返回子字符串的列表索引的函数

以下代码应满足您的要求。在其中详细说明了如何完成此操作。

# Lists that OP provided
lst1 = ["red","yellow","green","yellowhammer"]
lst2 = ["red","green"]

# Function that checks the list
def checkList(myList):
        # Create a variable to hold the concatenated string
        total = ""

        # Build the concatenated string
        for item in myList:
                total += item

        # Loop through the list again
        for i,item in enumerate(myList):
                # Count the amount of times each item appears in the concatenation
                curr = total.count(item)
                # If its more than one,since it will always appear once
                if(curr > 1):
                        # Return its index
                        return i
        # Otherwise,return False
        return False
# Test the two test samples
list_1_ans = checkList(lst1)
list_2_ans = checkList(lst2)

# Print out results
print("First Test Answer: {} | Second Test Answer: {}".format(list_1_ans,list_2_ans))

收益:

First Test Answer: 1 | Second Test Answer: False
,

以下函数将返回您需要的输出

def check_subs(lst1):
    answer = {1 if x in y and x !=y else 0 for x in lst1 for y in lst1}
    if sum(answer)>0:
        return answer
    else:
        return False
,

首先,要创建一个函数,您想使用def关键字。此函数以字符串列表作为输入,并返回boolint,因此带有类型提示的函数看起来像:

from typing import List,Union

def index_of_substring(strings: List[str]) -> Union[bool,int]:
    """The first index whose item is a substring of a different 
    item in the same list,or False if no such item exists."""
    # implement me
    pass

现在,我们需要根据其strings参数来实现函数的主体。由于我们要返回列表中的索引,因此遍历列表索引的range很有意义:

    for i in range(len(strings)):

此循环中的每个i都是一个索引(例如,在您的list1中,它将是一个从0到3的数字)。现在我们要问一个问题:“此索引处的项目是否是any本身以外的其他项目的子字符串?”

要回答该问题,我们想询问列表中可以与当前索引i进行比较的其他索引;我们将这些其他索引称为j

for j in range(len(strings))

以及相对于i我们想要满足的条件:

strings[i] in strings[j] and i != j

我们可以将所有内容放到列表理解中,这将为我们提供一个列表,该列表告诉我们范围内的哪些项目满足and条件:

[strings[i] in strings[j] and i != j for j in range(len(strings))]

,我们想知道其中的anyTrue

any([strings[i] in strings[j] and i != j for j in range(len(strings))])

如果是,我们要返回i。我们要对每个i重复此检查,如果 none 都不为真,我们想返回False。完整的功能如下:

def index_of_substring(strings: List[str]) -> Union[bool,int]:
    for i in range(len(strings)):
        if any([strings[i] in strings[j] and i != j for j in range(len(strings))]):
            return i
    return False

我们可以这样称呼它:

print(index_of_substring(lst1))
print(index_of_substring(lst2))

打印:

1
False
本文链接:https://www.f2er.com/3123260.html

大家都在问