Home > database >  Loop through list to extract specific patterns
Loop through list to extract specific patterns

Time:12-03

I have a quite specific question that I'm unsure about how to go forward with.

I have a list of numbers and I want to extract some specific patterns from them where I loop through the list and create a new one, it's easier to explain with an example.

Say I have a list, a = [2, 9, 3, 2, 3, 5, 7, 9].

What I want to do with this list is loop through 4 numbers at a time and give them corresponding letters, depending on when they occur in the sequence.

i.e. First four numbers = 2932 = ABCA

Second sequence of numbers = 9323 = ABCB

Third sequence = 3235 = ABAC

Fourth sequence = 2357 = ABCD

Fifth sequence = 3579 = ABCD

I then want to take these sequences and add them to another list which would now look like,

b = [ABCA, ABCB, ABAC, ABCD, ABCD]

I'm really unsure about how the format of the code should be, the length of the new list will always be 3 less than the original. Any help would be great, thanks.

CodePudding user response:

You can use a dictionary to assign letters to numbers and read that dictionary again to access the relevant letters. It has 2 loops, which is not ideal but it does the job:

a = [2, 9, 3, 2, 3, 5, 7, 9]
len_a = len(a)
output = []
letters = 'ABCD'
for i in range(len_a-3):
    d = {}
    k = 0
    for j in a[i:i 4]:
        if j not in d:
            d[j] = letters[k]
            k  = 1
        else:
            continue
    letter_assignment = ''.join([d[j] for j in a[i:i 4]])
    output.append(letter_assignment)
    

Output:

print(output)
# ['ABCA', 'ABCB', 'ABAC', 'ABCD', 'ABCD']

CodePudding user response:

I recommend using zip function for corresponding the numbers with the letters, while for the loop, use the "for" function.

  • Related