Python 如何检查单词是否在列表中,以及它是否存在于列表的某个项目中,然后获取该项目的索引号
我有一张名单叫aPython 如何检查单词是否在列表中,以及它是否存在于列表的某个项目中,然后获取该项目的索引号,python,python-3.x,list,Python,Python 3.x,List,我有一张名单叫a A = ["How are you","I am good","What are you doing?"] 我想搜索一个单词“good”,如果在列表中找到它,那么我想获取该单词所在的项目索引号 期望输出: A = ["How are you","I am good","What are you doing?"] B = "good" 结果=> 在列表A[1]中找到“好”字 我想获取在其中找到单词的列表项的索引号。您可以尝试以下操作: A = ["How are you",
A = ["How are you","I am good","What are you doing?"]
我想搜索一个单词“good”,如果在列表中找到它,那么我想获取该单词所在的项目索引号
期望输出:
A = ["How are you","I am good","What are you doing?"]
B = "good"
结果=>
在列表A[1]中找到“好”字
我想获取在其中找到单词的列表项的索引号。您可以尝试以下操作:
A = ["How are you","I am good","What are you doing?"]
B = "good"
d = [(i, a) for i, a in enumerate(A) if B in a]
print("Elements found", d[0][-1]) #printing what elements contain "good"
print("'{}' was found in list A[{}]".format(B, d[0][0]) if d else "'{}' not found".format(B))
输出:
'Elements found', 'I am good'
'good' was found in list A[1]
试试这个(我做了一个函数):
希望这有帮助 如果B=“you”?使用Ajax1234的方法,因为它可能更快,并且使用的代码行比mineUse少,而不是手动计算索引。如何打印出找到单词的列表项?在底部添加以下行:print(“找到的句子{}是{}”。格式(B,A[indexofword]))我如何打印出这个单词的列表中的项目?如果你不想捕捉意外的点击,比如“GooDes”,那么你可以考虑在A.SPLITE()中使用< <代码> > /代码>…
A = ["How are you","I am good","What are you doing?"]
B = "how"
def FindWordInList(list,item):
index = 0
for string in list:
index += 1
for word in string.split():
if word.lower() == item:
#Subtracts one from the list as list index starts at 0
return index - 1
print("Could not find the word {} in the list".format(item))
indexofword = FindWordInList(A,B)
print("{} word was found in list A[{}]".format(B,indexofword))