So I have two lists in python,
letters = ['1', '2', '4', '5', '7', '8']
list = ['3', '6', '9']
and I would like to merge these two lists into one. That looks like so:
['1', '2', '3', '4', '5', '6', '7', '8', '9']
Here is the code I am running
letters = ['1','2','4','5','7','8']
list = ['3','6','9']
new_list = []
n = 2
length = len(list)
i = 0
while i < length:
for start_index in range(0, len(letters), n):
new_list.extend(letters[start_index:start_index n])
print(list[i])
new_list.append(list[i])
i = 1
new_list.pop()
print(new_list)
which results in:
['1', '2', '3', '4', '5', '6', '7', '8']
whilst I am expecting
['1', '2', '3', '4', '5', '6', '7', '8', '9']
also the order is not alpha-numeric, the goal is to iterate through the smaller list and place each item into every 3rd slot of the larger list.
CodePudding user response:
Assuming that the numbers given are just placeholders, and not meant to actually be sorted:
One way to interleave items would be using iterators manually:
letters = ['1','2','4','5','7','8']
lst = ['3','6','9']
a = iter(letters)
b = iter(lst)
new_list = []
try:
while True:
if len(new_list) % 3 == 2:
new_list.append(next(b))
else:
new_list.append(next(a))
except StopIteration:
pass
Or for an entirely different, more terse, solution, you could use itertools.chain
alongside zip()
:
import itertools
letters = ['1','2','4','5','7','8']
lst = ['3','6','9']
new_list = list(itertools.chain(*zip(letters[::2], letters[1::2], lst)))
# letters[::2] -> 1, 4, 7
# letters[1::2] -> 2, 5, 8
# lst -> 3, 6, 9
#
# zip(...) -> (1, 2, 3), (4, 5, 6), (7, 8, 9)
# chain(...) -> 1, 2, 3, 4, 5, 6, 7, 8, 9
CodePudding user response:
I have edited your own code and used for
loop instead of while
:
letters = ['1','2','4','5','7','8']
myList = ['3','6','9']
new_list = []
length = len(myList) len(letters)
j = 0
for i in range(1,length 1):
if i % 3 == 0:
new_list.append(myList[i//3 - 1])
j -= 1
else:
new_list.append(letters[i j - 1])
print(new_list)
Output
['1', '2', '3', '4', '5', '6', '7', '8', '9']
Let's have another example:
letters = ['a','b','c','d','e','f']
myList = ['1','2','3']
new_list = []
length = len(myList) len(letters)
j = 0
for i in range(1,length 1):
if i % 3 == 0:
new_list.append(myList[i//3 - 1])
j -= 1
else:
new_list.append(letters[i j - 1])
print(new_list)
Output
['a', 'b', '1', 'c', 'd', '2', 'e', 'f', '3']
Note that this only works when the number of elements in the myList
variable will be multiple of 3.
CodePudding user response:
In Python 3.10, you can use itertools.pairwise
:
import itertools
letters = ['1','2','4','5','7','8']
new = ['3', '6', '9']
result = []
for pair, single in zip(itertools.pairwise(letters), new):
result.extend(pair)
result.append(single)
Or more generally (and for a pairwise replacement for before 3.10):
def by_n(iterable, n):
return zip(*[iter(iterable)]*n)
result = []
for triple, single in zip(by_n(letters, 3), new):
result.extend(triple)
result.append(single)