mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
我需要包含'aa'的所有项目的索引位置。我在将enumerate()与部分字符串匹配相结合时遇到了麻烦。我甚至不确定我是否应该使用枚举。
我只需要返回索引位置:0,2,5
答案 0 :(得分:94)
indices = [i for i, s in enumerate(mylist) if 'aa' in s]
答案 1 :(得分:14)
您使用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]
答案 2 :(得分:10)
没有enumerate()
:
>>> mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
>>> l = [mylist.index(i) for i in mylist if 'aa' in i]
>>> l
[0, 2, 5]
答案 3 :(得分:0)
spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]
index=spell_list.index("Annual")
print(index)