如何检查单词是否在列表中,如果它存在于列表的项目中,则获取该项目的索引号

时间:2017-09-29 21:05:39

标签: 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]

中找到了“好”字

我想获得找到该单词的列表项目的索引号。

2 个答案:

答案 0 :(得分:1)

试试这个(我做了一个功能):

json_encode()

希望这有帮助!

答案 1 :(得分:0)

你可以试试这个:

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]