Как сделать все элементы списка int python
Перейти к содержимому

Как сделать все элементы списка int python

  • автор:

Преобразование списка строк в список целых чисел в Python

В этом посте мы обсудим, как преобразовать список строк в список целых чисел в Python.

Например, список [«1», «2», «3», «4», «5»] следует преобразовать в список [1, 2, 3, 4, 5] .

1. Использование map() функция

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

Как преобразовать строковый список в целочисленный список в Python

Самый питонический способ преобразовать список строк в список INTS – это использование понимания списка [INT (X) для X в строках]. Это итерации по всем элементам в списке и преобразует каждый элемент X в списке в целочисленное значение, используя встроенный функцию int (x). Эта статья показывает вам самые простые … Как преобразовать строковый список в список целых в Python Подробнее »

  • Автор записи

Автор оригинала: Chris.

Самый питонический способ преобразовать Список строк к Список ints это использовать список пониманий [int (x) для x в строках] . Это итерации по всем элементам в списке и преобразует каждый элемент списка х до целочисленного значения, используя int (x) Встроенная функция.

Эта статья показывает вам простейших способов Преобразовать одномерное Список состоящий только из строк в список ints Отказ

Проблема : Учитывая список строк [«1», «2», «-3»] . Как преобразовать его в список ints [1, 2, -3] ?

  • Проблема Вариант: Учитывая список строк со смешанными представлениями [«1», «2.0», «-3.4»] . Как преобразовать его в список ints [1, 2, -3] ?

Сначала мы погрузимся в более легкую базовую проблему и изучить вариант проблемы в Метод 5 Отказ

Метод 1: Понимание списка

Предположим, у нас есть список:

Теперь проверьте тип элемента первого списка:

Давайте применим Встроенный Функция int () и получите список целых чисел, используя Понимание списка :

�� Понимание списка является компактным способом создания списков. Простая формула – [Выражение + контекст] Отказ Выражение : Что делать с элементом каждого списка? Контекст : Какие элементы для выбора? Контекст состоит из произвольного количества для и Если заявления.

Вы можете смотреть, как я объяснил список списков в этом видео:

Проверьте тип номеров в новом списке:

Встроенная функция int () Преобразует строку в целое число. Таким образом, это помогает нам создать новый список INTS из списка строк в Одна линия кода Отказ

Метод 2: Функция карты

Встроенная функция карта Хорошо оптимизирован и эффективен, когда он вызывается, элементы списка извлекаются при доступе. Следовательно, один элемент хранится и обрабатывается в памяти, что позволяет программе не хранить весь список элементов в системе память Отказ

Применить к одному списку А Следующий код:

�� карта () Функция применяет первый аргумент, функцию, к каждому элементу в итерателе. Он преобразует каждый элемент в оригинале, который потенциал для нового элемента и возвращает новый ИТЕРИТЕЛЬНО карта объект преобразованных значений. Чтобы получить список, вам нужно преобразовать его, используя встроенный Список () конструктор.

Вы можете наблюдать за моим видеочтером функции карты здесь:

Метод 3: для петли

Конечно, вы также можете конвертировать Список строк к Список ints Используя простой для петли Отказ Это то, что большинство людей, поступающих от языка программирования, такие как Java и C ++, будут делать, так как они не знают самых питоновых способов использования Понимание списка Тем не менее (см. Метод 1 ).

Этот базовый метод преобразовать Список строк к Список целых чисел Использует три шага:

  • Создайте пустой список с ints = [] .
  • Итерация за каждая строковый элемент с использованием для петля, такая как Для элемента в списке Отказ
  • Преобразуйте строку в целое число, используя int (элемент) и добавить его в новый целочисленный список, используя list.append () метод.

Способ 4: список пометки + EVAL ()

Вы также можете использовать Eval () Функция в списке понимание для преобразования списка строк в список INTS:

�� Встроенный Python Eval (ы) Функция разрабатывает строковый аргумент S В выражение питона запускает его и возвращает результат выражения. Если «выражение» – это простое целочисленное представление, Python преобразует аргумент S целому числу.

Вы можете наблюдать за мной, представляя Ins и ауты Eval () Функция в этом кратком направлении:

Метод 5: смешанное изображение строки с округлением

Проблема Вариант: Учитывая список строк со смешанными представлениями [«1», «2.0», «-3.4», «3.6»] . Как преобразовать его в список ints [1, 2, -3, 4] ?

Задача состоит в том, чтобы сначала преобразовать каждую строку на поплавок и только затем преобразуйте его в целое число. Эти два шага являются неотъемлемой частью, и никто не может быть пропущен, потому что вам нужно, чтобы поплавок был способен представлять любой номер. Но вам также нужно целое число, так как это цель, которую вы изложили: преобразование списка строк в список INTS.

❗ Конвертировать Список смешанных строковых представлений к Список закругленные целые числа это, цепляя Встроенный Функции раунд () и поплавок () в оформлении Понимание списка выражение [раунд (поплавок (ы)) для S в A] Предполагая, что список представления смешанного строка хранится в переменной А Отказ

Вы можете узнать все о раунд () Функция в следующем видео:

Чтобы увеличить свои навыки Python навыки, не стесняйтесь присоединиться к моей бесплатной академии электронной почты с большим количеством бесплатного контента и читовных листов – если вы еще этого не сделали! ��

Если вы хотите пойти по всему и изучать Python во время оплаты в процессе, проверьте мой курс Freelancer Python – номер один внештатный разработчик в мире!

Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.

Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python одноклассники (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.

Его страсти пишут, чтение и кодирование. Но его величайшая страсть состоит в том, чтобы служить стремлению кодер через Finxter и помогать им повысить свои навыки. Вы можете присоединиться к его бесплатной академии электронной почты здесь.

Python Convert List of Strings to Ints

Our first example would be implementing the naïve method to convert a list of strings to an integer. It is identified as the most generic method to convert a string-type list to an integer-type list. It has been achieved by applying a simple loop using type casting on the list for conversion. So, we have created a new Python project and initialized a list called “List” of five string elements. This list has been displayed using the print function. After that, we have set up a “for” loop that runs from 0 to the list’s length. On every iteration, the element of the list “List” has been converted into the integer type using type casting and saved to the same index of list “List”. An updated type cast new list has been printed out, as shown:

Run the previous code by utilizing the “Run” button of the Spyder 3 held at the menu bar. After running this file, we have the following result. The string type old list has been displayed first, and after that, the new and type casted list has been displayed on the console, such as string type and list type:

Example 02: Using Map Function

Our second and most efficient method to convert a string-type list to an integer-type list is using the map() function in our code. The map() method has been used specifically for conversion. So, within the Python code, we have defined an integer type list. The print function has been printing the original string-type list, such as List. The map function has been used to convert the index to an integer by passing it as an argument on the following line. This method takes every single element of a string separately to convert. After conversion, the data would be converted into a list once again. The resultant list would be saved into the variable “result”. At the last line, the updated integer-type list would be displayed using the print clause:

After running the code, we have the string-type list and integer-type list on the output console, as shown in the image.

Example 03: List Comprehension Method

This method is quite similar to the first method but somewhat direct to convert a string-type list to an integer-type list. We have started this example by initializing a string-type list having different values in it. Firstly, the string list would be showed on the console utilizing the print statement. Then, we have applied the list comprehension method on the list to get it converted into an integer-type list. Each value at index “I” of a list would be converted into an integer using the “int(i)” clause of for loop. A new list “List” would be inserted with the updated values. The integer-type list is then printed out in the console of Spyder 3 using the “List” in the parameter of a print() function:

After running the code, we have the string-type list first, and after that, we have got the integer-type list:

Как сделать все элементы списка int python

Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the entire list of strings to integers is quite common in the development domain. Let’s discuss a few ways to solve this particular problem.

Method 1: Using eval()

Python eval() function parse the expression argument and evaluate it as a python expression and runs Python expression(code), If the expression is an int representation, Python converts the argument to an integer.

Python3

Output:

Method 2: Naive Method

This is the most generic method that strikes any programmer while performing this kind of operation. Just looping over the whole list and converting each string of the list to int by type casting.

Python3

Output:

Method 3: Using list comprehension

This is just a kind of replica of the above method, just implemented using list comprehension, a kind of shorthand that a developer looks for always. It saves the time and complexity of coding a solution.

Python3

Output:

Method 4: Using map()

This is the most elegant, pythonic, and recommended method to perform this particular task. This function is exclusively made for this kind of task and should be used to perform them.

Python3

Output:

Method 5: List of strings with mixed integer representations

Here, we will first convert each string to a float first and then we will convert it into an integer by using the round() function, otherwise, it will throw error.

Python3

Output:

Method 6: Using the ast.literal_eval() function from the ast module

Another approach that can be used to convert a list of strings to a list of integers is using the ast.literal_eval() function from the ast module. This function allows you to evaluate a string as a Python literal, which means that it can parse and evaluate strings that contain Python expressions, such as numbers, lists, dictionaries, etc.

Here is an example of how to use ast.literal_eval() to convert a list of strings to a list of integers:

Python3

The time complexity of using the ast.literal_eval() function from the ast module to convert a list of strings to a list of integers is O(n), where n is the length of the list. This means that the time required to execute this approach is directly proportional to the size of the input list.

In terms of space complexity, this approach has a space complexity of O(n), because it creates a new list of integers that is the same size as the input list.

Approach: Using numpy.array() function

  1. Define a list of strings
  2. Convert the list to a numpy array of type int using the numpy.array() function
  3. Convert the numpy array back to a list using list() function
  4. Print the modified list

Python3

Output:

Time Complexity: The time complexity of this approach is O(n), where n is the length of the list. The numpy.array() function takes O(n) time to create a new array, and the list() function takes O(n) time to convert the array back to a list.

Space Complexity: The space complexity of this approach is O(n), because it creates a new numpy array of type int that is the same size as the input list.

Approach: Using the json.loads() function:

Algorithm:

  1. Create a list of strings test_list with the values [‘1’, ‘4’, ‘3’, ‘6’, ‘7’]
  2. Use the join() method to join the strings in test_list together with commas, resulting in the string ‘1,4,3,6,7’
  3. Add square brackets around the resulting string, resulting in the string ‘[1,4,3,6,7]’
    Use the loads() method from the json library to parse the string as a JSON array, resulting in the list [1, 4, 3, 6, 7]
  4. Assign the resulting list to new_list
  5. Print the string “Modified list is : ” followed by the string representation of new_list

Python3

The time complexity: O(n), where n is the length of test_list. This is because the join() method takes O(n) time to concatenate the strings, and the loads() method takes O(n) time to parse the resulting string.

The space complexity: O(n), since the resulting list takes up O(n) space in memory.

Approach: using re module

step-by-step algorithm for the regular expression approach to extract numerical values from a list of strings

  1. Define an input list of strings.
  2. Define a regular expression pattern to match numerical values in the strings.
  3. Initialize an empty list to store the converted numerical values.
  4. Iterate over each string in the input list.
  5. Use the regular expression pattern to search for a numerical value in the string.
  6. If a match is found, extract the matched substring and convert it to a float.
  7. Append the converted value to the output list.
  8. Once all strings in the input list have been processed, return the output list.

Python3

Time complexity: The time complexity of this approach is O(nm), where n is the number of strings in the input list and m is the maximum length of any string in the list. The regular expression pattern needs to be applied to each string in the list, which takes O(m) time in the worst case. Therefore, the overall time complexity is O(nm).
Auxiliary space complexity: The auxiliary space complexity of this approach is O(k), where k is the number of numerical values in the input list. We need to store each converted numerical value in the output list, which requires O(k) space. In addition, we need to store a regular expression object, which requires constant space. Therefore, the overall auxiliary space complexity is O(k).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *