【问题标题】:Split string and take only part of it (python)拆分字符串并仅提取其中的一部分(python)
【发布时间】:2021-04-11 18:42:38
【问题描述】:

问题

我有一个字符串列表,我们称之为input_list,这个列表中的每个字符串都由五个单词组成,只用一个“%”字符分隔,比如

"<word1>%<word2>%<word3>%<word4>%<word5>"

我的目标是,对于 input_list 的每个元素,制作一个仅由 &lt;word3&gt;&lt;word4&gt; 组成的字符串除以“%”符号,就像这样"&lt;word3&gt;%&lt;word4&gt;",并创建一个由这些字符串组成的新列表。 例如,如果:

input_list = ['the%quick%brown%fox%jumps', 'over%the%lazy%dog%and']

那么新列表将如下所示

new_list = ['brown%fox', 'lazy%dog']

重要说明和可能的答案

  • 每个单词的长度是随机的,所以我不能只使用字符串切片或以任何方式猜测&lt;word3&gt;&lt;word4&gt; 是如何开始的。
  • 一种可能的方法来回答这个问题,但我想知道是否有更好并且可能(计算上)更快的方法,而不必创建新变量(current_list)和/或不必考虑/拆分整个字符串(也许使用正则表达式?)
input_list = ['the%quick%brown%fox%jumps', 'over%the%lazy%dog%and']
new_list = []
for element in input_list:
    current_list = element.split('%')
    final_element = [current_list[2], current_list[3]]
    new_list.append(final_element)

编辑:

我尝试比较@Pac0 答案的运行时间和@bb1 答案的运行时间,并且,对于100 个字符串的输入列表,@Pac0 的运行时间为 92.28286 秒,@bb1 的运行时间为42.6106374 秒。所以我会考虑@bb1 一个作为答案。

【问题讨论】:

  • @00 通过这样做,我只是创建了一个字符串而不是一个列表,它不回答“重要说明和可能的答案”中写的问题

标签: python python-3.x string list


【解决方案1】:
new_list = ['%'.join(w.split('%')[2:4]) for w in input_list]

【讨论】:

    【解决方案2】:

    这个怎么样?

    input_list = ['the%quick%brown%fox%jumps', 'over%the%lazy%dog%and']
    new_list = ['%'.join(x.split('%')[2:4]) for x in input_list]
    print (new_list)
    

    输出

    ['brown%fox', 'lazy%dog']
    

    【讨论】:

      【解决方案3】:

      您可以将正则表达式 (regex) 与捕获组一起使用:

      import re
      
      pattern = re.compile('[^%]*%[^%]*%([^%]*%[^%]*)%[^%]*')
      input_list = ['the%quick%brown%fox%jumps', 'over%the%lazy%dog%and']
      
      result = [pattern.search(s).group(1) for s in input_list]
      print(result)
      

      注意:“编译”部分不是必需的,但如果您要处理大量字符串,则可以提高性能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-15
        相关资源
        最近更新 更多