Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
拆分字符串并仅获取其一部分(python) 问题:_Python_Python 3.x_String_List - Fatal编程技术网

拆分字符串并仅获取其一部分(python) 问题:

拆分字符串并仅获取其一部分(python) 问题:,python,python-3.x,string,list,Python,Python 3.x,String,List,我有一个字符串列表,我们称之为input\u list,这个列表中的每个字符串由五个单词组成,每个单词只除以一个“%”字符,如 "<word1>%<word2>%<word3>%<word4>%<word5>" 然后新列表将如下所示 new_list = ['brown%fox', 'lazy%dog'] 重要提示和可能的答案 每个单词的长度都是随机的,所以我不能仅仅使用字符串切片或以任何方式猜测和如何开始 回

我有一个字符串列表,我们称之为input\u list,这个列表中的每个字符串由五个单词组成,每个单词只除以一个“%”字符,如

"<word1>%<word2>%<word3>%<word4>%<word5>"
然后新列表将如下所示

new_list = ['brown%fox', 'lazy%dog']
重要提示和可能的答案
  • 每个单词的长度都是随机的,所以我不能仅仅使用字符串切片或以任何方式猜测
    如何开始
  • 回答这个问题的一种可能的方法如下,但我想知道是否有更好的、可能(计算上)更快的方法,而不必创建新变量(当前_列表)和/或不必考虑/拆分整个字符串(可能使用正则表达式?)
编辑: 我试图将@Pac0-answer的运行时间与@bb1-answer的运行时间进行比较,在100个字符串的输入列表中,@Pac0的运行时间为92.28286秒,@bb1的运行时间为42.6106374秒。所以我会考虑@ BB1作为答案。< / P > P如何?

new_list = ['%'.join(w.split('%')[2:4]) for w in input_list]
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']
这个怎么样

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']

可以将正则表达式(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)

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

您可以将正则表达式(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)

注意:“编译”部分不是严格需要的,但是如果你有很多字符串要处理,它可以提高性能。

@00这样做,我只是创建一个字符串而不是列表,它不会回答“重要注意事项和可能的答案”中写的问题@00这样做,我只是创建一个字符串而不是列表,它没有回答“重要注意事项和可能的答案”中的问题