Conditional substring of items in a list (Python)

CAA :

I have 2 lists. The first is my data list, and the second is a list of randomly generated numbers:

alist = ['ABCDEF', 'GHIJKL', 'MNOPQR', 'STUVWX']
blist = [2,0,3,1]

I want to substring 3 characters from each item in alist based on the values from blist.

My desired outcome:

['CDE', 'GHI', 'PQR', 'TUV']

How can I substring X characters from one list based on starting motif locations described in a different list?

Edit:

The following function accomplishes my desired outcome, but is there a better way to accomplish this task?

x = -1
clist = []
for i in alist:
    tracker = 1
    x = x + tracker
    substring = i[blist[x]:blist[x]+3]
    clist.append(substring)
WangGang :

Here is a solution:

output = []
for x in range(len(alist)):
    index = blist[x]
    output.append(alist[x][index:index+3])

How this program works:

First, it runs through the loop for the length of alist. The index position that you want to analyze is the x value of blist. Finally, append to an output list the first three characters from the index position in alist.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=194778&siteId=1