Python сложить элементы двух массивов

8 методов для сложения и объединения списков в Python

В этой теме мы обсудим методы для сложения и объединения двух или более списков с разными функциями в Python. Прежде чем перейти к рассмотрению концепций, давайте кратко познакомимся со списком Python. Список Python — это набор нескольких элементов, сгруппированных под одним именем. Он может хранить элементы данных различных типов (целые, строковые, с плавающей запятой и т. д.) внутри квадратных скобок [], разделенных запятой(,).

Объединение списков Python

Программа для печати списка Python

# list of characters List1 = ['A', 'B', 'C', 'D', 'E'] # list of integers List2 = [1, 2, 3, 4, 5,] # mixed lists List3 = ['A', 1, 'C', 'E', 5, 8] print(" Display the List1 ", List1) print(" Display the List2 ", List2) print(" Display the List3 ", List3)
Display the List1 ['A', 'B', 'C', 'D', 'E'] Display the List2 [1, 2, 3, 4, 5] Display the List3 ['A', 1, 'C', 'E', 5, 8]

Когда мы объединяем два или более списков вместе в программе Python, получается объединенный список. И этот процесс называется составлением или объединением списков.

Давайте обсудим различные способы объединения двух или более списков в Python:

  • Объединяйте списки в Python с помощью функции join() и разделителей.
  • Присоединяйтесь к списку с помощью функции join() без разделителей.
  • Присоединяйтесь к списку двух целых чисел в Python с помощью функции map().
  • Объедините два списка в Python, используя цикл for и функцию append().
  • Объедините несколько списков с помощью метода itertools.chain().
  • Соединяйте списки с помощью оператора(+).
  • Соедините два списка в Python с помощью оператора умножения(*).
  • Объедините списки с помощью функции extend().

Объединение списков с помощью функции join()

Функция join() используется для присоединения повторяющегося списка к другому списку, разделенному указанными разделителями, такими как запятая, символы, дефис и т. д.

str_name: это имя разделителя, разделяющего повторяющийся список.

iterable: это список, который содержит набор элементов и объединяется с разделителем.

Возвращаемое значение: возвращает объединенный список, разделенный указанными разделителями.

Примечание. Если итерируемый список содержит какие-либо нестроковые значения или элементы, он вызывает исключение TypeError.

Программа для объединения двух списков с помощью функции join() и разделителя

List1 = [ "Apple", "Orange", "Banana", "Mango", "Grapes" ] Str2 = ", " # It is the comma delimiter # use join() function to join List1 with the " . " delimiter Str2 = Str2.join( List1) # print the join list print(" Display the concatenated List1 using join() function and delimiter", Str2) List2 = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday" ] Str3 = " - " # It is the hyphen delimiter # use join() function to join List2 with the " - " delimiters Str3 = Str3.join( List2) # print the join list print(" Display the concatenated List2 using join() function and delimiter", Str3)
Display the concatenated List1 using join() function and delimiter Apple, Orange, Banana, Mango, Grapes Display the concatenated List2 using join() function and delimiter Sunday - Monday - Tuesday - Wednesday - Thursday

Программа для присоединения к списку без использования разделителя

# declare a python list Lt1 = [ 'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't' ] print( " Display the elements of the List L1 " , Lt1) L2 = ' ' # declare any empty string without defining any delimiter Ret = L2.join( Lt1) # use join method to join L1 list with L2 print( " Display the List without using delimiters", Ret)
Display the elements of the List L1 ['j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't'] Display the List without using delimiters j a v a t p o i n t

Присоединение к списку двух целых чисел с помощью функции map()

Целочисленный список: он собирает все целые числа в списке, называемом целочисленным списком, и мы не можем объединить два целочисленных списка в Python с помощью функции join(). Поэтому мы используем функцию map(), которая преобразует целочисленный список в строку. После этого мы используем функцию join() для объединения результатов функции map() с соответствующими разделителями.

Читайте также:  Размеры в CSS3

В приведенном выше синтаксисе функция map() имеет два параметра: list_name и str. Где list_name — это имя списка целых чисел, а str — строка. Функция map() преобразует list_name в строку (str).

Программа для использования функции map() и функции join() в списке

Давайте создадим программу для преобразования заданного списка целых чисел в строку, используя функцию map(), а затем функцию join() для присоединения к списку.

lt = [1, 2, 3, 4, 5] # use map() function to convert integer list into string list_map = map(str, lt) lt2 = ', ' # use join() function to join lists and delimiter comma(,) res = lt2.join(list_map) print(" Display the concatenated integers list using map() and join() function ", res)
Display the concatenated integers list using map() and join() function 1, 2, 3, 4, 5

Программа для объединения двух списков в Python с помощью цикла for и функции append()

Функция append() используется для последовательного добавления или присоединения каждого элемента повторяющегося списка в конце другого списка с помощью цикла for. Давайте создадим простую программу для добавления элементов списка в конец другого списка с помощью функции append().

List1 = [1, 2, 3, 4, 5] # declare List1 List2 = [5, 6, 7, 8, 9, 10] # declare List2 print(" Given List1 ", List1) print(" Given List2 ", List2) # use for loop to iterate each element of Lt1 to l2 for i in List2: List1.append(i) # use append() function to insert each elements at the end of Lt1 print(" Display concatenation list using append() function ", List1)
Given List1 [1, 2, 3, 4, 5] Given List2 [5, 6, 7, 8, 9, 10] Display concatenation list using append() function [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10]

Объединение нескольких списков с использованием метода itertools.chain()

Давайте создадим простую программу на Python для объединения нескольких списков с помощью метода chain(), импортировав пакет itertools.

# use Python itertools.chain() method to join two list import itertools # declare different lists a = [1, 2, 3, 4, 5] b = [6, 7, 8, 9, 10] c = [11, 12, 13, 14, 15] print(" Display the first list ", a) print(" Display the second list ", b) print(" Display the third list ", c) # use itertools.chain() method to join the list result = list(itertools.chain(a, b, c)) # pass the result variable in str() function to return the concatenated lists print(" Concatenated list in python using itertools.chain() method ", str(result))
Display the first list [1, 2, 3, 4, 5] Display the second list [6, 7, 8, 9, 10] Display the third list [11, 12, 13, 14, 15] Concatenated list in python using itertools.chain() method [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

Программа для объединения двух списков с помощью оператора +

Рассмотрим пример объединения двух списков в Python с помощью оператора(+) плюс.

# Create a program to join two lists in Python using the '+' operator # declare two lists of characters list1 = [ 'A', 'B', 'C', 'D', 'E'] list2 = [ 'F', 'G', 'H', 'I', 'J'] # join two characters lists using '+' operator lt_sum1 = list1 + list2 # declares two lists of integers list3 = [ '1', '2', '3', '4', '5'] list4 = [ '6', '7', '8', '9', '10'] # join two integers lists using '+' operator lt_sum2 = list3 + list4 # display the concatenation list print(" Join two list of characters in Python using + operator: ", str(lt_sum1)) # display the concatenation list print(" Join two list of integers in Python using + operator: ", str(lt_sum2))
Join two list of characters in Python using + operator: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] Join two list of integers in Python using + operator: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

Объединение двух списков с оператором умножения(*)

Рассмотрим пример объединения двух списков в Python с помощью оператора *.

# declare two lists of characters List1 = [ 'A', 'B', 'C', 'D', 'E'] List2 = [ 'F', 'G', 'H', 'I', 'J'] print(" Display character List1 ", List1) print(" Display character List2 ", List2) # join two characters lists using '*' operator lt_sum1 = [*List1, *List2] # declares two lists of integers List3 = [ 1, 2, 3, 4, 5] List4 = [ 6, 7, 8, 9, 10] print(" Display integer List3 ", List3) print(" Display integer List4 ", List4) # join two integers lists using '*' operator lt_sum2 = [*List3, *List4] # display the concatenation list print(" Join two characters list in Python using * operator: "+ str(lt_sum1)) # display the concatenation list print(" Join two integers list in Python using * operator: "+ str(lt_sum2))
Display integer List3 [1, 2, 3, 4, 5] Display integer List4 [6, 7, 8, 9, 10] Join two characters list in Python using * operator: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] Join two integers list in Python using * operator: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Метод extend() для объединения двух списков в Python

Напишем простую программу для объединения двух списков с помощью метода extend() в Python.

# takes two integers lists List1 = [5, 10, 5] List2 = [ 2, 4, 6, 8] print(" Display the List1 ", List1) print(" Display the List1 ", List2) # takes two string lists List3 = [ 'RED', 'BLUE', 'BLACK'] List4 = [ 'BROWN', 'PURPLE', 'GREY' ] print(" Display the List3 ", List3) print(" Display the List4 ", List4) # use extend() method to join two lists List1.extend(List2) List3.extend(List4) # print concatenation lists print( "\n Adding two lists of integers in Python using the extend() function: ", str(List1)) print( "\n Adding two lists of strings in Python using the extend() function: ", str(List3))
Display the List1 [5, 10, 5] Display the List1 [2, 4, 6, 8] Display the List3 ['RED', 'BLUE', 'BLACK'] Display the List4 ['BROWN', 'PURPLE', 'GREY'] Adding two lists of integers in Python using the extend() function: [5, 10, 5, 2, 4, 6, 8] Adding two lists of strings in Python using the extend() function: ['RED', 'BLUE', 'BLACK', 'BROWN', 'PURPLE', 'GREY']

Источник

Оцените статью