以下代码应满足您的要求。在其中详细说明了如何完成此操作。
# 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
关键字。此函数以字符串列表作为输入,并返回bool
或int
,因此带有类型提示的函数看起来像:
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))]
,我们想知道其中的any
是True
:
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