Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert values in lists following a pattern

Tags:

python

I have the following example list:

list_a = [(1, 6), 
          (6, 66), 
          (66, 72), 
          (72, 78), 
          (78, 138), 
          (138, 146), 
          (154, 208), 
          (208, 217), 
          (217, 225), 
          (225, 279), 
          (279, 288)
          .....
          ]

And what I need is:

  1. After every 6 elements on a list, insert in this place a new tuple formed by the last number of the previous one, and the first number in the previous 6 tuples.
  2. After the tuple inserted, insert another with formed by the first number of the previous one plus 1, and by the last number of the previous one and the first number of the next tuple.

so the result may look like:

list_a = [(1, 6), 
          (6, 66), 
          (66, 72), 
          (72, 78), 
          (78, 138), 
          (138, 146),
          (146, 1),     # <- first part 
          (147, 154),   # <- second part
          (154, 208), 
          (208, 217), 
          (217, 225), 
          (225, 279), 
          (279, 288)
          (288, 147)     # <- first part
          .....
          ]

I have tried this, but the last last elements are missing

for i in range(0, len(list_a)+1, 6):
    if i > 0:
        list_a.insert(i, (list_a[i - 1][1], list_a[i - 6][0]))
        list_a.insert(i + 1, (list_a[i - 1][1] + 1, list_a[i + 1][0],))
like image 423
efirvida Avatar asked Dec 17 '25 17:12

efirvida


1 Answers

I would just build a new list by constantly appending to it rather than inserting into an existing list. This should work:

n = len(list_a)
newList = []
for i in range(0,n, 6):
    newList.append(list_a[i:i+6] ) 

    newTuple1 = (newList[-1][1], newList[i][0])
    newList.append(newTuple1)
    try:
        newTuple2 = (newTuple1[0] + 1, list_a[i+6][0])
        newList.append(newTuple2)
    except IndexError:
        print "There was no next tuple"

print newList

Output

There was no next tuple
[(1, 6), (6, 66), (66, 72), (72, 78), (78, 138), (138, 146), (146, 1), (147, 154), (154, 208), (208, 217), (217, 225), (225, 279), (279, 288), (300, 400), (400, 146)]

Note that your example did not indicate what to do in case two if there are no additional tuples. Supposed there are 12 tuples in list_a. Then when you get to the second group of 2, there is no next tuple.

Hope that helps.

like image 170
Garrett R Avatar answered Dec 19 '25 06:12

Garrett R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!