Python 如何以不规则的间隔将字符串拆分为列表

Python 如何以不规则的间隔将字符串拆分为列表,python,Python,我试图通过使用间隔列表拆分字符串,在与字符索引对应的第一个间隔值之前插入一个空格,在与字符索引对应的第二个间隔值之后插入一个空格 我知道如何定期拆分字符串: 字符串='anexample' 结果=[] 对于0范围内的i,lenstring,2: 结果。追加“” 结果.附录行[i:i+2] 结果=['','an','','ex','','am','','pl','','e'] 但我不确定如何使用这样的间隔列表: 字符串='anexample' 结果=[] 间隔列表=[[0,0],[2,5]] 结果

我试图通过使用间隔列表拆分字符串,在与字符索引对应的第一个间隔值之前插入一个空格,在与字符索引对应的第二个间隔值之后插入一个空格

我知道如何定期拆分字符串:

字符串='anexample' 结果=[] 对于0范围内的i,lenstring,2: 结果。追加“” 结果.附录行[i:i+2] 结果=['','an','','ex','','am','','pl','','e'] 但我不确定如何使用这样的间隔列表:

字符串='anexample' 结果=[] 间隔列表=[[0,0],[2,5]] 结果是:

结果=['','a','','n','','','exam','','','ple'] 任何帮助都将不胜感激,谢谢

编辑:间隔列表是通过将列表中的字符与字符串进行比较得到的,例如:

字符串='anexample' 单词列表=[“考试”] 间隔列表=[[2,5]] 其中字符串[2]=“e”和字符串[5]=“m”。在“e”之前和“m”之后添加空格将给出:

结果=['an','','exam','','ple']
假设间隔始终按顺序列出:

string = 'anexample'
result = []
interval_list = [[0,0],[2,5]]

for i,interval in enumerate(interval_list):
    # append the part of the string before the first interval (if any)
    if i < 1 and interval[0] > 0:
        result.append(string[0:interval[0]])

    result.append(' ')
    result.append(string[interval[0]:interval[1]+1])
    result.append(' ')

    # append the part of the string before the next interval (if any)
    if i < len(interval_list) - 1 and (interval_list[i+1][0]>interval[1]+1):
        result.append(string[interval[1]+1:interval_list[i+1][0]])

    # append the rest of the string to result
    elif i == len(interval_list) - 1 and i < len(string)-1:
        result.append(string[interval[1]+1:len(string)])

print(result)
嗯,你的间歇时间清单让人很不舒服。应该是这样的

lst = [0, 1, 2, 6, 9]
然后你可以简单地做

for a, b in zip(lst[:-1], lst[1:]):
    result.extend([' ', string[a:b]])

# print(result)
# [' ', 'a', ' ', 'n', ' ', 'exam', ' ', 'ple']
你完成了

如果你对区间列表的结构没有影响,你可以通过

lst = [i for sub in interval_list for i in sub]
for i in range(1, len(lst), 2):
    lst[i] += 1
lst += [len(string)]

# [0, 1, 2, 6, 9]
或者你可能已经导入了numpy

lst = np.array(interval_list).flatten()
lst[1::2] += 1
lst = np.append(lst, len(string))

如果间隔列表从0开始,则可以使用以下代码:

string = 'anexample'
result = []
interval_list = [[0,0],[2,5]]

for i in range(len(interval_list)) :
    current_interval = interval_list[i]
    result.append(" ")
    result.append(string[current_interval[0]:current_interval[1]+1])
    result.append(" ")
    if i < len(interval_list) - 1 :
        next_interval = interval_list[i+1]
        result.append(string[current_interval[1]+1:next_interval[0]])
    if i == len(interval_list) - 1 :
        if string[current_interval[1]+1:] is not '' :
            result.append(string[current_interval[1]+1:])

output : [' ', 'a', ' ', 'n', ' ', 'exam', ' ', 'ple']

你的间隔列表是什么意思?我的间隔列表包含现有字符的索引范围,在本例中,我在另一个列表中有单词“exam”,它对应于字符串“anexample”的索引2到5。@tiqtoq所以你想根据间隔拆分字符串吗?@DirtyBit correct,因此,如果我有字符串'example'和一个区间[2,4],我会像这样拆分字符串:'ex'+space+'amp'+space+'le',在字符串的第二个索引之前和第四个索引之后添加一个空格。为什么要嵌套区间列表?[0,0]是什么?在我的例子中,我要拆分的间隔是专门分组的,在我的示例中,您格式的间隔列表看起来像lst=[0,0,2,5]。对于ziplst[:-1]中的a,b,lst[1:]行给出了间隔0,0,0,2和2,5,而我只需要0,0和2,5.No。对不起,你完全误解了整件事,请再仔细阅读一遍。1.在您的示例中,我的格式的间隔列表看起来像lst=[0,1,2,6,9],即:第一个起始索引0,第一个结束索引0+1,因为在python中,索引包括起始索引和不包括停止索引,然后是第二个起始索引2,然后是第二个停止索引5+1,最后是一个附加索引,即字符串9的长度。2.知道这一点,以及你不能更改列表的事实,我甚至向你建议了一个简短的转换器:只要运行这4行,你就有了lst…我的错误,误解了lst的格式。谢谢你的澄清。没问题,不客气。但是现在我想你明白了我所说的“不舒服”是什么意思了:代码变得多么简短和容易,这仅仅是因为区间列表的结构适应了这个问题。这种方法的好处是它不会局限于从0开始的区间列表。它可以普遍应用。
string = 'anexample'
result = []
interval_list = [[0,0],[2,5]]

for i in range(len(interval_list)) :
    current_interval = interval_list[i]
    result.append(" ")
    result.append(string[current_interval[0]:current_interval[1]+1])
    result.append(" ")
    if i < len(interval_list) - 1 :
        next_interval = interval_list[i+1]
        result.append(string[current_interval[1]+1:next_interval[0]])
    if i == len(interval_list) - 1 :
        if string[current_interval[1]+1:] is not '' :
            result.append(string[current_interval[1]+1:])

output : [' ', 'a', ' ', 'n', ' ', 'exam', ' ', 'ple']
string = 'anexample'
result = []
interval_list = [[0,0],[2,5]]


# Step 1:turn string into element list
string_list = list(string) #['a', 'n', 'e', 'x', 'a', 'm', 'p', 'l', 'e']

# Step 2: we want to insert " " according to the interval_list, but each time we insert one element, the next index
#will be influenced. So we convert the index into a new_interval_list that can predict the possible change
new_interval_list =  [[None for _ in range(2)] for _ in range(2)] # it should have identical shape to the interval_list

for i in range(len(interval_list)):
    #print(str(i))
    for j in range(2):
        #print(str(j))
        if j == 0: # first interval in a list
            new_interval_list[i][j] = interval_list[i][j] + i * 2
            #print(new_interval_list)
        else: # second interval in a list
            new_interval_list[i][j] = interval_list[i][j] + 2 + i * 2
            #print(new_interval_list)

# the new_interval_list returns [[0, 2], [4, 9]]

# Step 3: we turn [[0, 2], [4, 9]] into [0,2,4,9]
import itertools
new_interval_list = list(itertools.chain.from_iterable(new_interval_list))

# Step 4: now we can insert " " into the list
for item in new_interval_list:
    string_list.insert(item," ")
    # [' ', 'a', ' ', 'n', ' ', 'e', 'x', 'a', 'm', ' ', 'p', 'l', 'e']

# Step 5: to get ['a', 'n', 'exam', 'ple']

tem_l = ("".join(string_list)).split() # ['a', 'n', 'exam', 'ple']

# step 6: get result, add " " between each item in the tem_l
for i in range(4):
    result.append(" ")
    result.append(tem_l[i])


result