简体   繁体   中英

how can we fill all empty list inside the list in python from another list element?

have a list like this

> lst1=[1,2,3]
> lst2=[[],['abc','bcd','acd'],[],['sdf','ghj','klh'],[]]

want output like :

> [[1],['abc','bcd','acd'],[2],['sdf','ghj','klh'],[3]]

have tried to split the list of 2nd list and then aggregating by

One approach:

lst1=[1,2,3]
lst2=[[],['abc','bcd','acd'],[],['sdf','ghj','klh'],[]]

it = iter(lst1)
for i in lst2[::2]:
    i.append(next(it))

print(lst2)

Output

[[1], ['abc', 'bcd', 'acd'], [2], ['sdf', 'ghj', 'klh'], [3]]

An alternative that returns a new list:

it = iter(lst1)
res  = [l if i % 2 == 1 else [*l, next(it)] for i, l in enumerate(lst2)]
print(res)

Output

[[1], ['abc', 'bcd', 'acd'], [2], ['sdf', 'ghj', 'klh'], [3]]

Here is an approach similar to that of Dani Mesajo. Make an iterator of the fill list, then pull the next item for empty lists.

l1 = iter([1, 2, 3])
l2 = [[], ["abc", "bcd", "acd"], [], ["sdf", "ghj", "klh"], []]

print([l or next(l1) for l in l2])

yields:

➜ python listfill.py
[1, ['abc', 'bcd', 'acd'], 2, ['sdf', 'ghj', 'klh'], 3]

This is my solution that checks if an element from lst2 is an empty list, and if it is, the corresponding item from lst1 is added to new_list , otherwise the corresponding item from lst2 is added. n is used as the index to use for lst1 , which is incremented each time an item from lst1 is added instead of an item from lst2 .

lst1=[1,2,3]
lst2=[[],['abc','bcd','acd'],[],['sdf','ghj','klh'],[]]
new_list = []
n = 0

for l in lst2:
    if len(l) == 0:
        new_list.append([lst1[n]])
        n += 1
    else:
        new_list.append(l)

print(new_list)

A simple loop will do the job:

Code:

import copy
lst1 = [1,2,3]
lst2 = [[],['abc','bcd','acd'],[],['sdf','ghj','klh'],[]]

merged_lst = copy.deepcopy(lst2)
for i in range(len(lst1)):
    merged_lst[i*2].append(lst1[i])
print(merged_lst)

Output:

[[1], ['abc', 'bcd', 'acd'], [2], ['sdf', 'ghj', 'klh'], [3]]

We've to check whether the inner list of lst2 is empty or not, if yes, add the element of lst1 to it. We'll do it using two loop. One loop for iterating lst1 and second to ieratw lst2. The moment we get empty list, we'll add element of lst1 to it. Your code:

lst1=[1,2,3]
lst2=lst2 = [[],['abc','bcd','acd'],[],['sdf','ghj','klh'],[]]
for i in lst1:
    for j in lst2:
        if len(j)==0:
            j.append(i)
            break          #break the inner for loop 

print(lst2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM