Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.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_Indexing - Fatal编程技术网

python:基于原始索引添加列表元素(更新列表时)

python:基于原始索引添加列表元素(更新列表时),python,indexing,Python,Indexing,我有这样一个序列: ABCDEFGHIJKL 我想插入以下字符串: '-(c0)-' after elements 1 and 3 '-(c1)-' after elements 2 and 4 '-(c2)-' after elements 5 and 6 这就是我写的代码: list_seq = list('ABCDEFGHIJKL') new_list_seq = list('ABCDEFGHIJKL') start_end = [(1,3), (2,4), (5,6)] for in

我有这样一个序列:

ABCDEFGHIJKL
我想插入以下字符串:

'-(c0)-' after elements 1 and 3
'-(c1)-' after elements 2 and 4
'-(c2)-' after elements 5 and 6
这就是我写的代码:

list_seq = list('ABCDEFGHIJKL')
new_list_seq = list('ABCDEFGHIJKL')
start_end = [(1,3), (2,4), (5,6)]
for index,i in enumerate(start_end):
    pair_name = '-(c' + str(index) + ')-'
    start_index = int(i[0])  
    end_index = int(i[1]) 
    new_list_seq.insert(start_index, pair_name)
    new_list_seq.insert(end_index, pair_name)
print ''.join(new_list_seq)
我想要的输出是:

AB-(c0)-C-(c1)-D-(c0)-E-(c1)-F-(c2)-G-(c2)-HIJKL
(其中c0插入位置1和3后,c1插入位置2和4后,c2插入位置5和6后)

但我得到的结果是:

A-(c0)--(c1)-B-(c1)--(c2)--(c2)--(c0)-CDEFGHIJKL
我认为可能的问题是,当我将一个项目合并到字符串中时,索引会发生变化,那么在第一个项目之后的所有后续包含都不在正确的位置

有人能解释一下如何正确地做到这一点吗

希望有帮助:

s = 'ABCDEFGHIJKL'
res = list()
for nr, sub in enumerate(s):
    res.append(sub)
    if nr in (1, 3):
        res.append('-(c0)-')
    elif nr in (2, 4):
        res.append('-(c1)-')
    elif nr in (5, 6):
        res.append('-(c2)-')
res = ''.join(res)        
print(res)    
# AB-(c0)-C-(c1)-D-(c0)-E-(c1)-F-(c2)-G-(c2)-HIJKL 

基于@r.user.05apr的一个非常好的想法,即逐字符逐步遍历整个输入字符串,我想添加一种可能性,将其推广到任意长的
开始\u结束
-列表:

s = 'ABCDEFGHIJKL'
res = list()
for nr, sub in enumerate(s):
    res.append(sub)
    try:
        i = [nr in x for x in start_end].index(True)
        res.append('-(c' + str(i) + ')-')
    except:
        pass
res = ''.join(res)        
print(res)    
# AB-(c0)-C-(c1)-D-(c0)-E-(c1)-F-(c2)-G-(c2)-HIJK

您也可以从最后一个到第一个依次插入元素。这样就不会更改要插入的下一项的目标索引。