These 12 ways to easily merge lists in Python

I like the number 12 because there are so many things related to 12. There are 12 months in a year; in ancient times, 12 hours (earthly branches) were used to express the time of a day. Use one epoch to represent 12 years; Greece has 12 main gods; Zodiac has 12 houses; Zecharia Siqin’s "Earth Chronicles" described in the 12th celestial body (Nibiru); in addition, friends, lovers, The strokes of lovers and family members are all 12.

These 12 ways to easily merge lists in Python These 12 ways to easily merge lists in Python

I like the number 12 because there are so many things related to 12. There are 12 months in a year; in ancient times, 12 hours (earthly branches) were used to express the time of a day. Use one epoch to represent 12 years; Greece has 12 main gods; Zodiac has 12 houses; Zecharia Siqin’s "Earth Chronicles" described in the 12th celestial body (Nibiru); in addition, friends, lovers, The strokes of lovers and family members are all 12. So 12 is destined to be an unforgettable number. Now I will add an unforgettable explanation to 12: Combine Python lists in 12 ways.

In fact, the method of merging two or more lists in Python is very simple, just use the plus sign (+) directly. However, in many scenarios, it is not suitable to use "+". The values ​​in the list are scattered due to some reasons, or need to be de-duplicated, or are in the process of iteration, so this article will show the reader how to merge two or more lists in as many as 12 ways.

Method 1: The first plus sign in the universe. This is the simplest way to merge Python lists. The code is as follows:

list1 = [1, 2, 3] 
list2 = [4, 5, 6] 
 
result = list1 + list2 
# [1, 2, 3, 4, 5, 6] 
print(result)

This method does not need to be explained, just add it directly, since it is fine to add two lists, of course it is also possible to add 10,000 lists, or put it in a loop and add continuously.

Method 2: Asterisk method of automatic unpacking and packing

Since Python 3.5, the asterisk (*) has a special purpose, to split a list, or to assemble multiple values ​​into tuples. If the asterisk is used as a list element, and this list element is also a list, then the value in the list will be directly inserted as an element into the upper-level list, the code is as follows:

list1 = [1, 2, 3] 
list2 = [4, 5, 6] 
 
result = list1 + list2 
# [1, 2, 3, 4, 5, 6] 
print(result) 

PS: Double stars (**) can disassemble the dictionary. If single stars and double stars are used as the parameters of the function, then it is boxing. Discrete values ​​can be assembled into tuples (single stars) and dictionaries (double stars). The code is as follows:

import itertools 
list1 = [1, 2, 3] 
list2 = [4, 5, 6] 
# Direct merger 
# [1, 2, 3, 4, 5, 6] 
result = [item for item in itertools.chain(list1, list2)] 
print(result) 
# When merging two lists, add 1 to the value of each list element 
# [2, 3, 4, 5, 6, 7] 
result = [item + 1 for item in itertools.chain( list1, list2)] 
print(result)

Method 3: Controllable merging, not to "iterate" whoever

The first two methods of merging lists are of course relatively simple, but the problem is that only simple merging can be done. If more complicated merging (such as processing specific list elements in the process of merging) is to be done, it cannot be done. Therefore, in this case, each list element can be processed separately in an iterative manner. I call this merging method a controllable merge. The code is as follows:

import itertools 
list1 = [1, 2, 3] 
list2 = [4, 5, 6] 
# Direct merger 
# [1, 2, 3, 4, 5, 6] 
result = [item for item in itertools.chain(list1, list2)] 
print(result) 
# When merging two lists, add 1 to the value of each list element 
# [2, 3, 4, 5, 6, 7] 
result = [item + 1 for item in itertools.chain( list1, list2)] 
print(result)

Method 4: Usefulness of forced conversion

Through the chain class, you can turn two or more lists into a chain object, and then convert the chain object into a list object. The code is as follows:

from itertools import chain 
list1 = [1, 2, 3] 
list2 = [4, 5, 6] 
result = list(chain(list1, list2)) 
# [1, 2, 3, 4, 5, 6] 
print(result) 

The prototype of the chain class construction method is as follows:

def __init__(self, *iterables) 

Obviously, the iterables parameter of the construction method uses a single star (*), so you can receive any number of list parameters, for example, chain(list1, list2, list3, list4, list5) is legal, so this method can merge any number Lists.

Method 5: I don’t need duplicate values

There is a special way of merging lists, that is, de-duplication, that is, if there are duplicate values ​​in the merged two or more lists, then only one identical value can be kept. In fact, the merged result becomes a collection. Therefore, a collection can be used to solve this problem. The code is as follows:

list1 = [1, 2, 3] 
list2 = [4, 3, 6] 
result = list(set(list1 + list2)) 
# [1, 2, 3, 4, 6] 
print(result) 

Although this method of merging lists uses the plus sign (+), it also uses the set, so it should belong to a new merging method, because this merging method meets a special requirement: de-duplication.

Method 6: Generator Dafa

The previous methods all use the ready-made mechanisms in Python, but now it is a bit more complicated: custom conversion functions.

This way of merging lists involves the following technologies:

1. Custom Python functions

2. Single star (*) as function parameter

3. Python Generator (Generator)

4. Type conversion implementation

code show as below:

list1 = [1, 2, 3] 
list2 = [4, 5, 6] 
list3 = [7, 8, 9] 
list4 = [10, 11, 12] 
list5 = ["hello", 20.1, True] 
# Combine function , Is also a generator 
def merge(*iters): 
    for it in iters: 
        yield from it 
result = list(merge(list1, list2,'abcd', [20, 21, 22],list3,list4,list5)) 
# [1, 2, 3, 4, 5, 6,'a','b','c','d', 20, 21, 22, 7, 8, 9, 10, 11, 12,'hello' , 20.1, True] 
print(result)

The merge of this code is a merge function in the form of a generator, and uses a single star (*) as the parameter type, so any number of lists can be passed in. This example merges 7 lists. Where'abcd' is a list in the form of a string, and each list element is a single character.

Method 7: See the for in expression again

Python simply takes for to the extreme, providing for in expressions. Note that this is an expression, not a statement. So it can be used in other expressions, for example, to generate a list with a for in expression, the code is as follows:

list1 = [1, 2, 3] 
list2 = [4, 5, 6] 
# If it is a letter, the corresponding ASCII will be output 
result = [ord(item) if str(item).isalpha() else item for item in ( list1 + list2 + list('abcd') + [20, 21, 22])] 
# [1, 2, 3, 4, 5, 6, 97, 98, 99, 100, 20, 21, 22] 
print( result)

This method is suitable for copying a new list, and specific list values ​​can be modified during the merging process.

Method 8: itself can also be modified

When merging lists, if you want a list itself to be modified, you can use this method. For example, after merging the two lists of A and B, A itself becomes the final modified result, that is, B is appended to the back of A. The implementation code is as follows:

list1 = [1, 2, 3] 
list2 = [4, 5, 6] 
result = [] 
result.extend(list1) 
result.extend(list2) 
# [1, 2, 3, 4, 5, 6] 
print(result) 
# [1, 2, 3, 4, 5, 6] 
list1.extend(list2) 
print(list1)

If you don't want to modify the list participating in the merge, you can define an empty list.

Method 9: The Python library is a good thing, there are treasures everywhere

Python has a very large function library, many of which are used to merge lists. The add function in the operator module is one of them. In fact, add internally uses the plus sign (+) to merge lists, but this should also be regarded as a kind of Method, because the add function may use other ways to merge lists in the future. code show as below:

import operator 
list1 = [1, 2, 3] 
list2 = [4, 5, 6] 
result = operator.add(list1, list2) 
# [1, 2, 3, 4, 5, 6] 
print(result)

Method 10: Far in the sky, close in front of you

I introduced a bunch of APIs for merging lists. In fact, the list class (list) itself has a __add__ method for merging two lists. The code is as follows:

list1 = [1,2,3] 
list2 = [4,5,6] 
 
result = list.__add__(list1, list2) 
# [1, 2, 3, 4, 5, 6] 
print(result)

Method 11: the traditional way

Here is the most traditional way to introduce so many ways to merge lists. In fact, the most traditional way is to add an element one by one, which is the append method of the list. So many students may ask, there are so many good ways, why do you want to add an element one by one? Does it affect efficiency? In fact, it depends on the situation. For example, in some scenes, the value of the list has been disassembled (to handle other services), then the append method is used to add them one by one, anyway, it has been disassembled, and no whitening is not added.

The implementation code is as follows:

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

Method 12: The merger method is not enough, foreign aid comes to collect

In fact, there are only so many ways to merge lists in Python. It seems that there are only 11 kinds. As mentioned earlier, there are 12 kinds. In order to make up 12 kinds, here is a foreign aid. This is NumPy. This library is mainly used for scientific computing. The processing of data is relatively powerful. The code to merge Python lists with NumPy is as follows:

import numpy 
list1 = [1,2,3] 
list2 = [4,5,6] 
 
result = numpy.concatenate([list1,list2]).tolist() 
print(result)

Since the numpy.concatenate function returns the numpy.ndarray type, to get the Python list object, you also need to use the tolist method to convert. NumPy is a third-party library, so you need to use the following command to install it.

pip install numpy 

Guess you like

Origin blog.csdn.net/yaxuan88521/article/details/115176122