Python implements method analysis for merging two lists

  • 2020-10-07 18:45:24
  • OfStack

This article shows an example of how Python implements merging two lists. To share for your reference, the details are as follows:

Read a blog post and see a problem: how to combine two lists.

Method 1

The most primitive and stupid method is to take all the elements from two lists and put them into a new list, OK. The sample code is as follows:


list1 = [1,2,3]
list2 = [4,5,6]
list_new = []
for item in list1:
  list_new.append(item)
for item in list2:
  list_new.append(item)
print list_new

The results of the action are as follows:

[

[1,2,3,4,5,6]

]

Method 2

One of the built-in functions in python is used here zip() , the function of which can be seen from the name, is to package several otherwise unrelated content into one. Cut the crap and look at the code:


a = [1,2,3]
b = [4,5,6]
c = zip(a,b) //c = [(1,4),(2,5),(3,6)]
list_new = [row[i] for i in range(len(0)) for row in c]

Pack first, then reduce dimensions, that's all. (In fact, 1 o 'clock is not easy. You will feel the impulse to hit someone when you see the back.)

Methods 3

I went to the end, only to find that what I had written before was nonsense. Why? Because python grammar can be achieved in one sentence, I even struggled with an article here, which was really boring.


a = [1,2,3]
b = [4,5,6]
c = a + b

That's it! That's bullshit!!

For more information about Python, please refer to Python String Manipulation Skills summary, Python Data Structure and Algorithm Tutorial, Python Function Using Skills Summary, Python Introduction and Advanced Classic Tutorial and Python File and Directory Operation Skills Summary.

I hope this article has been helpful in Python programming.


Related articles: