【发布时间】:2020-04-30 10:20:08
【问题描述】:
考虑一下,
text = 'lmn pqr xyz abc def pqr abc'
我需要从字符串str 中获取单词abc 出现的两个索引。
我试过text.split().index('abc'),得到的输出是3。
我需要3 和6 作为输出。
【问题讨论】:
标签: python python-3.x string
考虑一下,
text = 'lmn pqr xyz abc def pqr abc'
我需要从字符串str 中获取单词abc 出现的两个索引。
我试过text.split().index('abc'),得到的输出是3。
我需要3 和6 作为输出。
【问题讨论】:
标签: python python-3.x string
str = "lmn pqr xyz abc def pqr abc"
indices = [i for i, element in enumerate(str.split()) if element=="abc"]
print(indices)
输出
[3, 6]
首先拆分字符串并使其成为str.split() 的列表,然后它变为['lmn', 'pqr', 'xyz', 'abc', 'def', 'pqr', 'abc']。然后取分割后的str的每个元素及其索引位置,我们这里用for循环枚举。如果任何项目与“abc”匹配,则其索引位置将附加到索引列表中。
如果您想知道 str 中“abc”的总出现次数,请使用len(indices)
为了更好地理解,我在不使用列表理解的情况下编写上述代码:
str = "lmn pqr xyz abc def pqr abc"
indices = []
for i, element in enumerate(str.split()):
if element=="abc":
indices.append(i)
print(f"The index position of 'abc' are {indices}")
同样,如果你想找到所有项目的索引位置,那么试试这个:
str = "lmn pqr xyz abc def pqr abc"
deduped_str = set(str.split())
result = dict()
for item in deduped_str:
indices = [i for i, element in enumerate(str.split()) if element==item]
result[item] = indices
print(result)
【讨论】:
不要分配给str,因为它是一种类型。
这应该做你想做的事
>>> text = 'lmn pqr xyz abc def pqr abc'
>>> print([n for (n, e) in enumerate(text.split()) if e == 'abc'])
[3, 6]
【讨论】:
print [n for (n, e) in enumerate(text.split()) if e == 'abc']