1

I have three lists as seen below:

a = [0,0,0,0,0,1,1,1,1,1,2,2,2,2]
b = [1,2,3,5,6,7,7,4,3,2,1,2,2,3]
c = [3,4,5,2,5,7,8,2,1,3,4,7,3,8]

I want to append [b,c] to the corresponding index of a new list where a is the index, to clarify what I mean this is the desired result

data = [
  [[1,3],[2,4],[3,5],[5,2],[6,5]],
  [[7,7],[7,8],[4,2],[3,1],[2,3]],
  [[1,4],[2,7],[2,3],[3,8]]
]

As in data[0] = [b,c] where a is 0 and so on..

I am trying to implement this with the following code

n = list(set(a))
data= [[]]*len(n)
cnt = 0

for i in range(len(a)-1):
    if a[i] == a[i+1] and a[i] == cnt:
        data[cnt].append([b[i],c[i]])
    if a[i] != a[i+1] and a[i] == cnt:
        data[cnt].append([b[i],c[i]])
        cnt += 1

That gives me this answer:

data = [
  [[1, 3], [2, 4], [3, 5], [5, 2], [6, 5], [7, 7], [7, 8], [4, 2], [3, 1], [2, 3], [1, 4], [2, 7], [2, 3]], 
  [[1, 3], [2, 4], [3, 5], [5, 2], [6, 5], [7, 7], [7, 8], [4, 2], [3, 1], [2, 3], [1, 4], [2, 7], [2, 3]], 
  [[1, 3], [2, 4], [3, 5], [5, 2], [6, 5], [7, 7], [7, 8], [4, 2], [3, 1], [2, 3], [1, 4], [2, 7], [2, 3]]
]

But that doesn't give me the result I am seeking, any help is appreciated!

Austin
  • 25,759
  • 4
  • 25
  • 48
mb567
  • 691
  • 6
  • 21
  • What is wrong with the result this is giving you? Is `c[i],c[i]` a typo on the second-last line? Are you always missing the last element from your final array? – Welbog Oct 23 '18 at 18:19
  • I update the question showing the results I get with the above code. And yes I miss an element which I don't know how to fix, my iterator is bad I guess – mb567 Oct 23 '18 at 18:22

1 Answers1

1

Use zip to iterate over multiple lists simultaneously. Create empty sublists initially and then append to these lists:

A = [0,0,0,0,0,1,1,1,1,1,2,2,2,2]
B = [1,2,3,5,6,7,7,4,3,2,1,2,2,3]
C = [3,4,5,2,5,7,8,2,1,3,4,7,3,8]

lst = [[] for _ in range(max(A) + 1)]

for a, b, c in zip(A, B, C):
    lst[a].append([b, c])

print(lst)
# [[[1, 3], [2, 4], [3, 5], [5, 2], [6, 5]], [[7, 7], [7, 8], [4, 2], [3, 1], [2, 3]], [[1, 4], [2, 7], [2, 3], [3, 8]]]
Austin
  • 25,759
  • 4
  • 25
  • 48