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



我有一个这样的序列:

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

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

谁能解释如何正确地做到这一点?

基于 @r.user.05apr 的好主意,即简单地逐个执行整个输入字符串 char,我想添加一个可能性来概括任意长的start_end-list:

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

希望对您有所帮助:

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 

最新更新