Reputation: 360
I have a list of lists like the following:
[[11710000035, 11710000034], [11710000038, 11710000031, 11710000033], [11710000099]]
I'd like to merge all the sublist of length 1 with one of the other (it doesn't matter which one).
So, for example, I would like to obtain:
[[11710000035, 11710000034], [11710000038, 11710000031, 11710000033, 11710000099]]
or
[[11710000035, 11710000034, 11710000099], [11710000038, 11710000031, 11710000033]]
Any idea?
Upvotes: 1
Views: 657
Reputation: 2231
Another approach would be deleting 1 length elements from list and adding another list and appending those elements to our list's first element.
a = [[11710000035, 11710000034], [11710000038,
11710000031, 11710000033], [11710000099]]
x = []
for ind, item in enumerate(a):
if (len(item) == 1):
x.append(a[ind][0])
del a[ind]
if a:
a[0].extend(x)
print(a)
Upvotes: 1
Reputation: 540
This is a straightforward, not so elegant, potential solution:
l = [[11710000035, 11710000034], [11710000038, 11710000031, 11710000033], [11710000099]]
j = 0
for i, e in enumerate(l):
if len(e) > 1:
j = i
if len(e) == 1:
l[j] = l[j] + e
del l[i]
print(l)
Upvotes: 2
Reputation: 1266
Here is another approach. Care about length of data. If data length is less than 2 it throws an error
data = [[11710000035, 11710000034], [11710000038, 11710000031, 11710000033], [11710000099]]
for idx, sub_list in enumerate(data):
if(len(sub_list)==1):
if(idx!=0):
data[idx-1] += data.pop(idx)
else:
data[idx+1] += data.pop(idx)
print(data)
Upvotes: 1
Reputation: 7510
A variant using chain:
from itertools import chain
l = [[11710000035, 11710000034], [11710000038, 11710000031, 11710000033], [11710000099]]
big_lists = [i for i in l if len(i) > 1 ]
big_lists[0] += chain.from_iterable( i for i in l if len(i) == 1 )
Upvotes: 1
Reputation: 10819
Here is a solution in 2 steps.
First, collect all the items in the list with more than one element.
l = [[11710000035, 11710000034], [11710000038, 11710000031, 11710000033], [11710000099]]
r = [i for i in l if len(i) > 1]
Then add the single elements in one of the items of r
. Since it doesn't matter for you, I would simply add them to the first item in the list.
for i in l:
if len(i) == 1:
r[0] += i
print(r)
[[11710000035, 11710000034, 11710000099], [11710000038, 11710000031, 11710000033]]
Upvotes: 2
Reputation: 142
You can merge a list with +.
In your case:
result_list = [your_list[0]]
result_list.append(your_list[1] + your_list[2])
Upvotes: -2