【问题标题】:How to get multipleindices of a word which is occurring more than once in a string? [duplicate]如何获取在字符串中多次出现的单词的多个索引? [复制]
【发布时间】:2020-04-30 10:20:08
【问题描述】:

考虑一下,

text = 'lmn pqr xyz abc def pqr abc'

我需要从字符串str 中获取单词abc 出现的两个索引。

我试过text.split().index('abc'),得到的输出是3

我需要36 作为输出。

【问题讨论】:

标签: python python-3.x string


【解决方案1】:
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)

【讨论】:

    【解决方案2】:

    不要分配给str,因为它是一种类型。

    这应该做你想做的事

    >>> text = 'lmn pqr xyz abc def pqr abc'
    >>> print([n for (n, e) in enumerate(text.split()) if e == 'abc'])
    [3, 6]
    

    【讨论】:

    • 感谢回复,但是print语句好像有语法错误。
    • 正如您使用 Python 3.x 标记的那样,这是该版本 python 的语法。对于旧版本,请使用 print [n for (n, e) in enumerate(text.split()) if e == 'abc']
    猜你喜欢
    • 2019-09-16
    • 1970-01-01
    • 2021-05-03
    • 2021-07-14
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    相关资源
    最近更新 更多