2

I'm setting up a linear connection and I have two list:

a = [1,1,1,2,2,3,3,3,4]
b = [1,3,7,2,3,4,7,8,9]

a[i] related to b[i]

I regrouped b as c:

c = [[1, 3], [7], [2, 3], [4], [7, 8], [9]]

I tried to add the corresponding value of a in every sublist in c to get:

d = [[1, 1, 3], [1, 7], [2 ,2, 3], [3, 4], [3, 7, 8], [4, 9]]

The first value in every sublist of c that originally in b is related to a like c[0][0] = b[0], and add a[0] to c[0], c[1][0] = b[2], so add a[2] to c[1].

If sublist in c and the first value of the sublist = b[i], add a[i] to every sublist.

I got stuck for this.

asked Mar 27, 2019 at 9:42
2
  • 2
    Can you elaborate more on what you are trying to do? what is the relation between A and B. Why d has only three 1s but A and B have four altogether? Commented Mar 27, 2019 at 9:46
  • For every sublist in c, if sublist[0] = b[i], add a[i] to sublist. Is that Okay? Commented Mar 27, 2019 at 9:54

2 Answers 2

2

You could build an iterator from a and take successive slices of it using itertools.islice in order to consume it according to the length of the sublists in c, but only select the first item from each slice:

from itertools import islice
a = [1,1,1,2,2,3,3,3,4]
c = [[1, 3], [7], [2, 3], [4], [7, 8], [9]]
a_ = iter(a)
[[list(islice(a_, len(j)))[0]] + [i for i in j] for j in c]

Output

[[1, 1, 3], [1, 7], [2, 2, 3], [3, 4], [3, 7, 8], [4, 9]]
answered Mar 27, 2019 at 10:00
1

Another method. Basic Way.

#!/bin/python
a = [1,1,1,2,2,3,3,3,4]
b = [1,3,7,2,3,4,7,8,9]
c = [[1, 3], [7], [2, 3], [4], [7, 8], [9]]
#d = [[1, 1, 3], [1, 7], [2 ,2, 3], [3, 4], [3, 7, 8], [4, 9]]
element_count=0
d=[]
for x in c:
 print (a[element_count])
 print(x)
 d.append([a[element_count]]+x)
 element_count+=len(x)
answered Mar 27, 2019 at 10:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.