Float list to int list python

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

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

Самый питонический способ преобразовать список поплавков ФС К списку целых чисел – использовать одноклассник fs = [int (x) для x в fs] Отказ Это итерации по всем элементам в списке ФС Использование списка понимание и преобразует каждый элемент списка х до целочисленного значения, используя int (x) конструктор.

Читайте также:  Php api documentation script

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

Проблема : Учитывая список поплавков [1.0, 2.0, 3.0] Отказ Как преобразовать его в список ints [1, 2, 3] ?

Методы не применимы к спискам списков, они содержат ошибки округления, отличающиеся в каждом способе. При необходимости вы можете добавлять циклы или определить пользовательские функции для проверки, учет и минимизации ошибок.

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

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

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

Давайте применим встроенный функцию int и получите список целых чисел:

print([int(a) for a in a]) # [1, 1, 1, 0, 5, -2]

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

A = [int(a) for a in a] print(type(A[0])) #

Таким образом, используя встроенный функцию int , который преобразует реальное число раундов к нулю или, скорее, он отбрасывает дробную часть, мы можем получить новый список целых чисел с Код однонаправления Отказ

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

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

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

print(list(map(int, a))) # [1, 1, 1, 0, 5, -2]

Нет смысла проверять тип элементов результирующего списка, поскольку когда мы назвали функцию карты, мы передали функцию INT, уже описанную в методе 1 в качестве аргумента, и завернули результат в списке, используя Список функция.

Качество этого преобразования списка или, скорее, ошибка округления, такая же, как и в первом способе.

Способ 3: круглая и списка понимание

Это очень похоже на первый, но в отличие от int , это не просто отказывается от дробной части, но раунды до ближайшего даже целое число, если дробная часть составляет 0,5. Вы также можете пройти как второй аргумент Количество десятичных знаков, к которым требуется округление, по умолчанию это 0, это то, что мы будем использовать:

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

D = [round(a) for a in a] print(type(D[0])) #

Как видно из этого примера, есть разные встроенные функции для достижения нашей цели, разница в способе и величине ошибки округления.

Метод 4: математический модуль

Таким образом, я предлагаю использовать импортный модуль Математика , в котором мы будем использовать три функции Ceil () , пол () и trunch () Отказ Давайте приблизимся к каждому. У них один и тот же синтаксис, разница в пути округления.

Подам заявку в исходный список:

a = [1.1, 1.2, 1.8, 0.5, 5.9, -2.3] print([math.ceil(a) for a in a]) # [2, 2, 2, 1, 6, -2]

«Ceil» раунды до следующего крупнейшего целого числа, уважая знак ( -2.3 ).

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

C = [math.ceil(a) for a in a] print(type(C[0])) #

Рассмотрим следующую функцию в модуле «Math» – «Этаж», который является противоположностью «CEIL» – закругление до ближайшего целого числа:

print([math.floor(a) for a in a]) # [1, 1, 1, 0, 5, -3]
F = [math.floor(a) for a in a] print(type(F[0])) #

Следующая функция, trunch () аналогичен встроенному функции int () – Это просто отбрасывает дробную часть, что бы она ни была:

print([math.trunc(a) for a in a]) # [1, 1, 1, 0, 5, -2]
T = [math.trunc(a) for a in a] print(type(T[0])) #

Метод 5: Numpy

Вот посмотрите на преобразование списка из int на массив, используя Numpy модуль. Разница между массивом и списком состоит в том, что все элементы массива должны быть того же типа, например, «FLOAT» и «int». Числовые операции с большим количеством данных могут быть выполнены с массивами намного быстрее и эффективнее, чем со списками.

Давайте перевернем наш первый список А в массив:

import numpy as np N = np.array(a, int)

Мы передаем два аргумента в функцию массива, имя списка для преобразования в массив и тип для каждого элемента.

В отличие от int Тип номера в Python, модуль Numpy определяет их немного по-разному и разделен на несколько подгрупп. Например, ‘int32’ целые числа начиная от -2147483648 до 2147483647 (4 байтовых номера), ‘int64’ Числа от -92233720368547772036854775808 до 92233720368854775807 (8 байтовых номеров), есть также разные виды ‘int’ Для 32- и 64-битных операционных систем это необходимо учитывать при расчете с массивами.

Читайте ещё по теме:

Источник

Float list to int list python

Last updated: Feb 20, 2023
Reading time · 5 min

banner

# Table of Contents

# Convert a List of Floats to a List of Integers in Python

To convert a list of floats to a list of integers:

  1. Use a list comprehension to iterate over the list.
  2. Use the int() class to convert the current float to an integer.
  3. The new list will only contain integer values.
Copied!
list_of_floats = [1.23, 3.45, 5.67] result = [int(item) for item in list_of_floats] print(result) # 👉️ [1, 3, 5]

convert list of floats to list of integers

We used a list comprehension to iterate over the list of floats.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we pass the current float value to the int class to convert it to an integer.

The new list only contains integer values.

# Convert a List of Floats to a List of Integers using round()

You can also use the round() function to round each float to the nearest integer.

Copied!
list_of_floats = [1.23, 3.45, 5.67] result = [round(item) for item in list_of_floats] print(result) # 👉️ [1, 3, 6]

convert list of floats to list of integers using round

Instead of converting to an integer by dropping the decimal, this example converts the floating-point numbers in the list by rounding them to the nearest integers.

The round function takes the following 2 parameters:

Name Description
number the number to round to ndigits precision after the decimal
ndigits the number of digits after the decimal, the number should have after the operation (optional)

The round function returns the number rounded to ndigits precision after the decimal point.

If ndigits is omitted, the function returns the nearest integer.

Copied!
print(round(3.45)) # 👉️ 3 print(round(3.55)) # 👉️ 4

# Convert a List of Floats to a List of Integers using math.ceil

If you need to round up, use the math.ceil() method.

Copied!
import math list_of_floats = [1.23, 3.45, 5.67] result = [math.ceil(item) for item in list_of_floats] print(result) # 👉️ [2, 4, 6]

convert list of floats to list of integers using math ceil

The math.ceil method returns the smallest integer greater than or equal to the provided number.

Copied!
print(math.ceil(3.01)) # 👉️ 4 print(math.ceil(3.99)) # 👉️ 4

# Convert a List of Floats to a List of Integers using math.floor

If you need to round down, use the math.floor() method.

Copied!
import math list_of_floats = [1.23, 3.45, 5.67] result_4 = [math.floor(item) for item in list_of_floats] print(result_4) # 👉️ [1, 3, 5]

The math.floor method returns the largest integer less than or equal to the provided number.

Copied!
print(math.floor(4.999)) # 👉️ 4 print(math.floor(4.001)) # 👉️ 4

Alternatively, you can use the map() function.

# Convert a List of Floats to a List of Integers using map()

This is a three-step process:

  1. Pass the round() function and the list to the map() function.
  2. The map() function will pass each float to the round() function.
  3. Use the list() class to convert the map object to a list.
Copied!
list_of_floats = [2.4, 3.5, 6.7, 8.1] new_list = list(map(round, list_of_floats)) # 👇️ [2, 4, 7, 8] print(new_list)

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The map() function calls the round() function will each floating-point number in the list and rounds each value.

The last step is to use the list() class to convert the map object to a list.

The list() class takes an iterable and returns a list object.

Which approach you pick is a matter of personal preference. I’d go with the list comprehension as I find it more direct and easier to read.

# Convert a List of Integers to a List of Floats in Python

To convert a list of integers to a list of floats:

  1. Use a list comprehension to iterate over the list.
  2. Use the float() class to convert each integer to a float.
  3. The new list will only contain floating-point numbers.
Copied!
list_of_integers = [3, 5, 7, 9] new_list = [float(item) for item in list_of_integers] # 👇️ [3.0, 5.0, 7.0, 9.0] print(new_list)

We used a list comprehension to iterate over the list of integers.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we pass the integer to the float() class to convert it to a floating-point number.

The new list will only contain float values.

Alternatively, you can use the map() function.

# Convert a List of Integers to a List of Floats using map()

This is a three-step process:

  1. Pass the float() class and the list to the map() function.
  2. The map() function will call the float() class with each item in the list.
  3. Use the list() class to convert the map object to a list.
Copied!
list_of_integers = [3, 5, 7, 9] new_list = list(map(float, list_of_integers)) # 👇️ [3.0, 5.0, 7.0, 9.0] print(new_list)

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The float() class gets passed each integer in the list and converts each value to a floating-point number.

Lastly, we used the list() class to convert the map object to a list.

The list() class takes an iterable and returns a list object.

# Convert a List of Integers to a List of Floats using a for loop

You can also use a for loop to convert a list of integers to a list of floats.

Copied!
list_of_integers = [3, 5, 7, 9] new_list = [] for item in list_of_integers: new_list.append(float(item)) print(new_list) # 👉️ [3.0, 5.0, 7.0, 9.0]

On each iteration of the for loop, we convert the current item to a floating-point number and append the result to a new list.

# Convert a List of Integers to a List of Floats using NumPy

This is a two-step process:

  1. Pass the list and the float data type to the numpy.array() method.
  2. Optionally convert the NumPy array to a list.
Copied!
import numpy as np list_of_integers = [3, 5, 7, 9] new_list = list( np.array(list_of_integers, dtype=np.float32) ) # 👇️ [3.0, 5.0, 7.0, 9.0] print(new_list)

You can install NumPy by running the following command.

Copied!
pip install numpy # 👇️ or with pip3 pip3 install numpy

The numpy.array method creates an array from the provided object.

We set the dtype argument to np.float32 to specify the desired data type for the elements in the array.

The last (optional) step is to use the list() class to convert the NumPy array to a list object.

The list() class takes an iterable and returns a list object.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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