0

sorry this might be really simple but I can't think of a way to do it. I have a list like this:

    L = [('a', [[0],[1]]), ('b', [[2],[3]]), ('c', [[4],[5]])]

I want to iterate over L, forward extending the second item in each tuple. Which will give:

    L = [('a', [[0],[1]]), ('b', [[0], [1], [2],[3]]), ('c', [[0], [1], [2],[3], [4],[5]])]

I can't think of a way to this. Can someone help? Thanks

jaydh
  • 101
  • 1
  • 7

3 Answers3

2

Not sure if this is how you want it done, but this will do the job:

sum = []
for i,item in enumerate(L):
    sum += item[1]
    L[i] = (item[0], sum[:])
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • Thanks. I'm not very good with python and I need to run this on a huge list. Do you know which answer out of yours and sharshofski's is more efficient? – jaydh Feb 11 '15 at 17:19
1

Try this:

L = [('a', [[0],[1]]), ('b', [[2],[3]]), ('c', [[4],[5]])]
prev = []
for i,el in enumerate(L):
    el_new = (el[0], prev + el[1])
    prev += el[1]
    L[i] = el_new
sharshofski
  • 147
  • 6
  • @jaydh, for a rough time comparison of this v.s. similar code, you can try calling time.time() before/after this code and printing the difference. See [this post](http://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python) for an example. – sharshofski Feb 11 '15 at 18:00
0

Call this function with your list:

def extend(list):
    a = []
    extended_list = []
    for i in list:
        a += i[1]
        i = (i[0], a[:])
        extended_list.append(i)
   return extended_list
lonemc
  • 48
  • 4