Conditional substring of items in a list (Python)

Viewed 288

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)
3 Answers

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.

You can define a function to do this and make use of the built-in enumerate().


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


def substring_picker(list_a, list_b):
    # first create an empty list
    results = []

    # then loop over alist
    for i, element in enumerate(alist):
        # only pick elements with at least 3 chars
        if len(alist[i]) >= 3:
            # append the found chars to results list
            results.append(list_a[i][list_b[i]:list_b[i] + 3])

    return results


result = substring_picker(alist, blist)
print(result)

A short list comprehension using zip to link each 'count' with the item to be shortened, then index operators to select and prune the strings:

 [x[0][x[1]:][:3] for x in zip(alist, blist)]
Related