Reputation: 439
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.
Upvotes: 2
Views: 65
Reputation: 325
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)
Upvotes: 1
Reputation: 88226
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]]
Upvotes: 2