Python list cross-junction question.

Asked 2 years ago, Updated 2 years ago, 38 views

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]

python

2022-09-22 18:21

2 Answers

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']


2022-09-22 18:21

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. Link1 Link2

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)


2022-09-22 18:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.