Search code examples
pythonindexingdesign-patternsappend

Python list element patterns


I have a VERY simple question.

Honestly, I'm so sorry to ask you this stupid question but I really don't know how to do this.

I have a list like this.

p = [2, 5, 1, 2, 4, 1, 2, 5, 1, 2, 4, 1, 2, 4, 1, 2, 5, 1, 2, 4]

The elements in the list are usually the repetition of either 2, 4, 1 or 2, 5, 1.

Sometimes, there are no 1 at the end of 2, 4 or 2, 5.

I want to put 3 in the new list where the 3 consecutive elements of 2, 4, 1 or 2, 5, 1 are.

2, 4, 1 -> 3
2, 5, 1 -> 3

And I want to put 2 in the new list where the elements of 2, 4 or 2, 5 are.

2, 4 -> 2
2, 5 -> 2

Also, if there is either 2, 4 or 2, 5 at the end of the last 2, 4, 1 or 2, 5, 1, I need to put 3.

[2, 4, 1, 2, 5, 1, 2, 5] ==> [3, 3, 3]

However, if there are more than 2 of either 2, 4 or 2, 5 in a row after 2, 4, 1 or 2, 5, 1, I want to put 2 in the list like below.

[2, 4, 1, 2, 5, 2, 5] ==> [3, 2, 2]

My simple code below doesn't give me 2 at the end of the new list. Why is that?

Actually, I altered my code a lot and I am not getting what I want...

Any help will be GREATLY appreciated!

new_list = []

p = [2, 5, 1, 2, 4, 1, 2, 5, 1, 2, 4, 1, 2, 4, 1, 2, 5, 1, 2, 4] 

#p = [2, 5, 1, 2, 4, 1, 2, 5, 1, 2, 4, 1, 2, 4, 1, 2, 5, 1, 2, 4, 2, 4]
#p = [2, 4]

for i in range(0, len(p)):

    if i <= len(p) - 3:
        
        if p[i] == 2 and p[i+1] >= 4:
                
            if p[i+2] !=1:
                
                new_list.append(2)
                
            elif p[i+2] == 1:
            
                new_list.append(3)

            
print(new_list)

Solution

  • Let's do it step by step :

    new_list = []
    p = [2, 5, 1, 2, 4, 1, 2, 5, 1, 2, 4, 1, 2, 4, 1, 2, 5, 1, 2, 4]
    # p = [2, 4, 1, 2, 5, 1, 2, 5]
    # p = [2, 4, 1, 2, 5, 2, 5]
    
    
    sublists = []
    
    # First we split the list on each 2
    for i in p:
        if i == 2:
            sublists.append([2])
        else:
            sublists[-1].append(i)
    
    # Then we add the size of each sublist to the new list
    new_list = [len(x) for x in sublists]
    
    # This is the same as:
    # for i in sublists:
    #     new_list.append(len(i))
    
    # Finally we check the particular case of a 2 at the end of the new list
    if len(new_list) > 0 and new_list[-1] == 2:
        new_list[-1] = 3
        if len(new_list) > 1 and new_list[-2] == 2:
            new_list[-1] = 2
    
    print(new_list)
    
    

    It's often a good idea when you are dealing with multiple elements in a list to split it into sub-lists for more clarity.

    I hope you find that useful.