95
mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]

我需要所有包含'aa'. 我在enumerate()与部分字符串匹配结合时遇到问题。我什至不确定我是否应该使用枚举。

我只需要返回索引位置:0,2,5

4

4 回答 4

155

您可以enumeratelist-comprehension中使用:

indices = [i for i, s in enumerate(mylist) if 'aa' in s]
于 2013-02-13T08:29:31.360 回答
23

您的使用想法enumerate()是正确的。

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

或者,作为列表理解:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]
于 2013-02-13T08:28:48.113 回答
13

没有enumerate()

>>> mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
>>> l = [mylist.index(i) for i in mylist if 'aa' in i]
>>> l
[0, 2, 5]
于 2013-02-13T08:30:37.193 回答
-4
spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)
于 2019-03-07T19:49:21.940 回答