Home > Enterprise >  Adding an element from a list before and after the delimiter of another list
Adding an element from a list before and after the delimiter of another list

Time:11-12

There are 2 lists and my goal is to add the element from one list before and after the delimiters of another list. Below is the example:

ListA = ["A", "B"]
ListB = [[1, 2, 3, 4], [5, 6, 7, 8]]

Expected Output:

[[1, 'A', 2, 'A', 3, 'A', 4, 'A'], [5, 'B', 6, 'B', 7, 'B', 8, 'B']]

What I've done so far:

for x, y in zip(ListB, ListA):
    x.append(y)

Output: ListB

[[1, 2, 3, 4, 'A'], [5, 6, 7, 8, 'B']]

CodePudding user response:

Your code appends 'A' once to the whole [1,2,3,4] list. This should work:

ListA = ['A','B']
ListB = [[1,2,3,4],[5,6,7,8]]

for x, y in zip(ListB, ListA):
    for i in range(len(x)):
        x.insert(2*i 1,y)

print(ListB)
# [[1, 'A', 2, 'A', 3, 'A', 4, 'A'], [5, 'B', 6, 'B', 7, 'B', 8, 'B']]

A variant to produce something closest to your 2nd demand:

ListA = ['A','B','C'] 
ListB = [[1,5],[2,10],[11,15]]
for x, y in zip(ListB, ListA):
    for i in range(len(x)):
        x[i] = y   ' '   str(x[i])

print(ListB)
# [['A 1', 'A 5'], ['B 2', 'B 10'], ['C 11', 'C 15']]

CodePudding user response:

zip the two lists together, and then build new lists out of pairs of all the b items with the single a item:

>>> ListA = ['A','B']
>>> ListB = [[1,2,3,4],[5,6,7,8]]
>>> [[j for t in ((i, a) for i in b) for j in t] for a, b in zip(ListA, ListB)]
[[1, 'A', 2, 'A', 3, 'A', 4, 'A'], [5, 'B', 6, 'B', 7, 'B', 8, 'B']]

CodePudding user response:

Here is another approach to this:

from itertools import repeat

ListA = ["A", "B"]
ListB = [[1, 2, 3, 4], [5, 6, 7, 8]]

result = []
for x, y in zip(ListA, ListB):
    nested_list = []
    for item in zip(y, repeat(x)):
        nested_list.extend(item)
    result.append(nested_list)

print(result)

This can be written using a bit more complex list comp(Also this modifies ListB in-place instead of creating a new one):

from itertools import repeat

ListA = ["A", "B"]
ListB = [[1, 2, 3, 4], [5, 6, 7, 8]]

ListB[:] = [
    [i for item in zip(y, repeat(x)) for i in item] for x, y in zip(ListA, ListB)
]
print(ListB)
  • Related