查找列表中多个项目的索引

时间:2015-06-09 10:41:15

标签: python string list

我有一个清单

myList = ["what is your name", "Hi, how are you",
          "What about you", "How about a coffee", "How are you"]

现在我想搜索所有"How""what"的索引。我怎么能用Pythonic方式做到这一点?

2 个答案:

答案 0 :(得分:4)

听起来像是一行的Python能够做到的!

[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]

答案 1 :(得分:1)

这样可行,但假设您不关心区分大小写:

myList = ["what is your name","Hi, how are you","What about you","How about a coffee","How are you"]
duplicate = "how are you"
index_list_of_duplicate = [i for i,j in enumerate(myList) if duplicate in j.lower()]
print index_list_of_duplicate
     [1,4]