python - 基于部分字符串在列表中查找索引位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14849293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:39:00  来源:igfitidea点击:

python - find index position in list based of partial string

pythonlist

提问by L Shaw

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

I need the index position of all items that contain 'aa'. I'm having trouble combining enumerate() with partial string matching. I'm not even sure if I should be using enumerate.

我需要包含“aa”的所有项目的索引位置。我在将 enumerate() 与部分字符串匹配相结合时遇到了麻烦。我什至不确定是否应该使用枚举。

I just need to return the index positions: 0,2,5

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

采纳答案by StoryTeller - Unslander Monica

indices = [i for i, s in enumerate(mylist) if 'aa' in s]

回答by pemistahl

Your idea to use enumerate()was correct.

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

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

Alternatively, as a list comprehension:

或者,作为列表理解:

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

回答by TerryA

Without enumerate():

没有enumerate()

>>> mylist = ["aa123", "bb2322", "aa354", "cc332", "ab334", "333aa"]
>>> l = [mylist.index(i) for i in mylist if 'aa' in i]
>>> l
[0, 2, 5]

回答by user11167492

spell_list = ["Tuesday", "Wednesday", "February", "November", "Annual", "Calendar", "Solstice"]

index=spell_list.index("Annual")
print(index)