简体   繁体   中英

How do I extend all elements of a list to another list every Nth item

I am trying to find a way to insert all elements from a list every nth element of another. There are several post similar but they are for single elements of a list to another list. What I am trying to figure out is taking the following list:

l1 = ["a","b"]
l2 = ["j","k","l","m","n","o","p","q","r","s","t"u"]

And outputting them together:

["j","k","l","a","b","m","n","o","a","b","p","q","r","a","b","s","t","u"]

What I'm thinking would work is something that at least starts with:

for x in 1st:
    for i in range(len(l2)):
        2nd.extend(l1)

I know this doesn't work but I'm not sure how to implement this.

In the specific output above, the first list is added after every 3rd element. It doesn't have to be every third element but I'm just using that as an example.

Can someone educate me on how to do this?

EDIT: With the help of @Chris, I was able to find a 3rd party library called more_itertools and created a new code that does exactly what I was looking for. Here is what I came up with:

import more_itertools as mit

l1 = ["a","b"]
l2 = ["j","k","l","m","n","o","p","q","r","s","t","u"]

#We will place the elements of 1st after every two elements of 2nd 
l3 = list(mit.collapse(mit.intersperse(l1, l2, n=len(l1))))

Results:

>>> print(l3)
['j', 'k', 'a', 'b', 'l', 'm', 'a', 'b', 'n', 'o', 'a', 'b', 'p', 'q', 'a', 
'b', 'r', 's', 'a', 'b', 't', 'u']

I found that the intersperse function will allow the user to place an element into a separate list at the "nth" interval. In this example, I place the list of l1 in the l2 list after every second element (since len(l1) is equal to 2). The collapse function will take the list that was placed in l2 and put each element in order as a separate element.

Thank you to everyone that helped me with this. I enjoyed learning something new.

numpy has the ability to split a list into evenly distributed smaller lists. You can specify in np.array_split the list itself, adn the number of splits. Here I used math.floor to get the even number of times the n value goes into the length of the list. In this case you have n=3 and the list has 12 elements, so it will return 4 as the number of resulting sublists.

The [np.append(x,l1) for x.... part says to attach the values in l1 to the end of each sublist. and chain_from_iterable will mash all of them together, and you can render that as a list with list() .

It has the side effect of adding the l1 values at the very end as well, which if you don't want to you can use slicing to drop of the last n values where n is the length of the l1 list.

import numpy as np
import itertools
import math

n = 3
l1 = ["a","b"]
l2 = ["j","k","l","m","n","o","p","q","r","s","t","u"]
list(itertools.chain.from_iterable([np.append(x, l1) for x in np.array_split(l2,math.floor(len(l2)) / n)]))

or if you don't want to trailing append:

list(itertools.chain.from_iterable([np.append(x, 
                                              l1) for x in np.array_split(l2,
                                                                          math.floor(len(l2)) / n)]))[:-len(l1)]

Just iterate through every n'th element of list b and insert every iteration of list a.

    a = ["a", "b"]
    b = ["j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u"]
    
    n = 3  # where you want to insert
    
    while n < len(b):
        for i in range(len(a)):
            b.insert(n, a[i])
            n += 1  # increment n by 1 so 'b' insert after 'a'
        n += 3  # increment n by 3 every iteration to insert list a
    
    print(b)

Result: ['j', 'k', 'l', 'a', 'b', 'm', 'n', 'o', 'a', 'b', 'p', 'q', 'r', 'a', 'b', 's', 't', 'u']

list3 = []
n = 3

for x in range(1, len(list2)+1):
    if x%n == 0 and x != len(list2):
        list3.append(list2[x-1])
        for y in list1:
            list3.append(y)
    else:
        list3.append(list2[x-1])

print(list3)
list1= ["a","b"]
list= ["j","k","l","m","n","o","p","q","r","s","t","u"]
d=[]
for i in list:
    print(list.index(i))
    if ((list.index(i)+1)%3==0 and list.index(i)!=0):
        d.append(i)
        d.extend(list1)

    else:
        d.append(i)
print(d)
one = ["a","b"]
two = ["j","k","l","m","n","o","p","q","r","s","t","u"]

start =0
end = 3 #or whatever number you require
complete_list=[]
iterations = int(len(two)/3)
for x in range(iterations):
    sub_list= two[start:end]   
    start = start+3
    end= end+3
    complete_list.append(sub_list)
    if x < iterations-1:
        complete_list.append(one)
complete_list = flatten(complete_list)

There may be a shorter version of code to do this, but this will work as well.

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