list_n = ['1','2','3','4']
list_a = [A,B,C,D]
I want to create an array called list_s
by adding the above two arrays.
Can we cross the array and put it together?
The results you want are as follows
list_s = ['1',A,'2',B,'3',C,'4',D]
You can also use the chain function in itertools.
https://docs.python.org/2/library/itertools.html#itertools.chain
The chain function connects in order when there are multiple tuples and lists.
import itertools as it
list_n = ['1','2','3','4']
list_a = ['A','B','C','D']
list(it.chain(*zip(list_n, list_a)))
['1', 'A', '2', 'B', '3', 'C', '4', 'D']
I think the word "cross and combine" is called weave or interleave in English. I looked it up and found something like this. After all, the zip()
method is the key. list_n = ['1','2','3','4']
list_a = ['a','B','C','D']
# Operated on Python 2
list_s = [a for b in zip(list_n, list_a) for a in b]
# Operated on Python 3
list_ss = [*sum(zip(list_n, list_a),())]
print(list_s)
print(list_ss)
© 2024 OneMinuteCode. All rights reserved.