mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
我需要所有包含'aa'
. 我在enumerate()
与部分字符串匹配结合时遇到问题。我什至不确定我是否应该使用枚举。
我只需要返回索引位置:0,2,5
您可以enumerate
在list-comprehension中使用:
indices = [i for i, s in enumerate(mylist) if 'aa' in s]
您的使用想法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]
没有enumerate()
:
>>> mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
>>> l = [mylist.index(i) for i in mylist if 'aa' in i]
>>> l
[0, 2, 5]
spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]
index=spell_list.index("Annual")
print(index)