【问题标题】:How can i write a function to create a list of indexes of selected characters in a string我如何编写一个函数来创建字符串中选定字符的索引列表
【发布时间】:2021-12-10 08:17:49
【问题描述】:

我得到了一个字符串,我需要创建一个包含单词之间空格索引的列表函数。

【问题讨论】:

  • 到目前为止你尝试过什么?请提供一些代码,我们可以看到问题所在。
  • 1.这不是我们为您解决作业的地方。 2.您应该向我们提供您已经尝试过的内容,以便我们帮助您解决问题。另外为了解决您的问题,您可以像在 C 中那样迭代字符串(使用索引)并检查索引上的字符是否为空格,如果是,将其添加到列表中,如果不是,继续。

标签: python r jupyter-notebook anaconda anaconda3


【解决方案1】:

为了提高效率,你可以使用正则表达式库:

import re
[match.start() for match in re.finditer(' ', 'my string is here')]
# [2, 9, 12]

re.finditer 将在您的第二个字符串参数中搜索第一个参数的所有出现,这里是一个空格
然后您可以使用 ma​​tch.start()

在匹配对象中找到匹配的开始索引

这是查找所有空格,如果您想要第一个索引,即使两个单词之间有几个空格,这也不起作用,您可能想澄清您的问题

与另一个解决方案时间比较:

import re
from time import time

text = "long text my test text was about 20000 chars"
start = time()
indices = [match.start() for match in re.finditer(' ', text)]
print(f'regex time :: {time() - start}')

start = time()
indices = []
text_length = len(text)
index = 0
while index < text_length:
    index = text.find(' ', index)
    if index == -1:
        break
    indices.append(index)
    index += 1
print(f'str.find :: {time() - start}')

start = time()
indices = [i for i, c in enumerate(text) if c == " "]
print(f'enumerate :: {time() - start}')

# regex time :: 0.0004987716674804688
# str.find :: 0.0010783672332763672
# enumerate :: 0.0011782646179199219

在这个例子中,第一个解决方案大约快两倍(20000 字符文本)

【讨论】:

  • 我不太确定它是否“高效”......据我所知,正则表达式通常很慢。
  • 如果您有更快的解决方案,我很想拥有它!我正在编辑答案以添加速度比较
  • 你是对的,我无法让它更有效率:) ...干得好,谢谢你的澄清
【解决方案2】:

您可以在列表推导中使用 enumerate:

s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"

[i for i,c in enumerate(s) if c==" "]

[5, 11, 17, 21, 27, 39, 50]

【讨论】:

    【解决方案3】:

    您的问题并不完全清楚。

    假设您有一个字符串“abcdefgh”和一个列表 [2,3,6],并且您想在列表中的每个位置之前插入空格,您可以这样做:

    s = 'abcdefgh'
    idx = [2,3,6]
    start = 0
    out = []
    for stop in idx+[len(s)]:
        out.append(s[start:stop])
        start = stop
    ' '.join(out)
    

    输出:'ab c def gh'

    【讨论】:

      猜你喜欢
      • 2012-09-10
      • 2023-02-04
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 2017-03-04
      • 2021-07-10
      • 2020-10-04
      • 2012-01-11
      相关资源
      最近更新 更多