简体   繁体   中英

Python [x::y] slice operator - why doesn't work for me?

I have a list like this:

residL=['M', 'P', 'P', 'M', 'L', 'S', 'G', 'L', 'L', 'A', 'R', 'L', 'V', 'K', 'L', 'L', 'L', 'G', 'R', 'H', 'G', 'S', 'A', 'L', 'H', 'W', 'R', 'A', 'A', 'G', 'A', 'A', 'T', 'V', 'L', 'L', 'V', 'I', 'V', 'L', 'L', 'A', 'G', 'S', 'Y', 'L', 'A', 'V', 'L', 'A']

Desired output:

residL = ['M', 'P', 'P', 'M', 'L', 'S', 'G', 'L', 'L', 'A\n10', 'R', 'L', 'V', 'K', 'L', 'L', 'L', 'G', 'R', 'H\n20', 'G', 'S', 'A', 'L', 'H', 'W', 'R', 'A', 'A', 'G\n30', 'A', 'A', 'T', 'V', 'L', 'L', 'V', 'I', 'V', 'L\n40', 'L', 'A', 'G', 'S', 'Y', 'L', 'A', 'V', 'L', 'A\n50']

I can get this output with this piece of code:

for i in range(9,len(residL), 10):
    residL[i] = '%s\n%i'%(residL[i], i+1)

But I wanted to go fancy, so I tried the slice operator:

residL[9::10] = [x+'\n%i'%(residL.index(x)+1) for x in residL[9::10]] 

I got a strange result though:

residL = ['M', 'P', 'P', 'M', 'L', 'S', 'G', 'L', 'L', 'A\n10', 'R', 'L', 'V', 'K', 'L', 'L', 'L', 'G', 'R', 'H\n20', 'G', 'S', 'A', 'L', 'H', 'W', 'R', 'A', 'A', 'G\n7', 'A', 'A', 'T', 'V', 'L', 'L', 'V', 'I', 'V', 'L\n5', 'L', 'A', 'G', 'S', 'Y', 'L', 'A', 'V', 'L', 'A\n10']

I'm wondering how could it be fixed. Just for the sake of learning. :)

index is finding an earlier appearance of the same letter. Instead, use enumerate to track the index yourself.

residL=['M', 'P', 'P', 'M', 'L', 'S', 'G', 'L', 'L', 'A', 'R', 'L', 'V', 'K', 'L', 'L', 'L', 'G', 'R', 'H', 'G', 'S', 'A', 'L', 'H', 'W', 'R', 'A', 'A', 'G', 'A', 'A', 'T', 'V', 'L', 'L', 'V', 'I', 'V', 'L', 'L', 'A', 'G', 'S', 'Y', 'L', 'A', 'V', 'L', 'A']
residL[9::10] = [x+'\n%i'%((i+1)*10) for i, x in enumerate(residL[9::10])] 
residL
# => ['M', 'P', 'P', 'M', 'L', 'S', 'G', 'L', 'L', 'A\n10', 'R', 'L', 'V', 'K', 'L', 'L', 'L', 'G', 'R', 'H\n20', 'G', 'S', 'A', 'L', 'H', 'W', 'R', 'A', 'A', 'G\n30', 'A', 'A', 'T', 'V', 'L', 'L', 'V', 'I', 'V', 'L\n40', 'L', 'A', 'G', 'S', 'Y', 'L', 'A', 'V', 'L', 'A\n50']

Use enumerate to keep track of index

>>> [x if (i-9)%10 else x+f'\n{i+1}' for i,x in enumerate(residL)] 
['M', 'P', 'P', 'M', 'L', 'S', 'G', 'L', 'L', 'A\n10', 'R', 'L', 'V', 'K', 'L', 'L', 'L', 'G', 'R', 'H\n20', 'G', 'S', 'A', 'L', 'H', 'W', 'R', 'A', 'A', 'G\n30', 'A', 'A', 'T', 'V', 'L', 'L', 'V', 'I', 'V', 'L\n40', 'L', 'A', 'G', 'S', 'Y', 'L', 'A', 'V', 'L', 'A\n50']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM