Slowat_Kela
Slowat_Kela

Reputation: 1511

python: Add list elements based on original indexing (while updating list)

I have a sequence like this:

ABCDEFGHIJKL

I would like to insert the strings:

'-(c0)-' after elements 1 and 3
'-(c1)-' after elements 2 and 4
'-(c2)-' after elements 5 and 6

This is the kind of code I was writing:

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)

The output I would want is:

AB-(c0)-C-(c1)-D-(c0)-E-(c1)-F-(c2)-G-(c2)-HIJKL

(where c0 was inserted after 1 and 3 positions, c1 was inserted after 2 and 4, and c2 was inserted after 5 and 6).

But the output I get is:

A-(c0)--(c1)-B-(c1)--(c2)--(c2)--(c0)-CDEFGHIJKL

I think possibly the problem is that as I incorporate an item into the string, the indices change, so then all subsequent inclusions after the first one are not in the right positions?

Could anyone explain how to do this properly?

Upvotes: 1

Views: 36

Answers (2)

SpghttCd
SpghttCd

Reputation: 10860

Based on @r.user.05apr's very good idea to simply step through the whole input string char by char, I'd like to add a possibility to generalize this for an arbitrary long 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

Upvotes: 1

r.user.05apr
r.user.05apr

Reputation: 5456

Hope it helps:

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 

Upvotes: 1

Related Questions