Как преобразовать массив в число python
Перейти к содержимому

Как преобразовать массив в число python

  • автор:

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

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

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

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

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

Как преобразовать массив в число 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 through error.

Convert list of ints to one number?

I have a list of integers that I would like to convert to one number like:

What is the best way to implement the magic function?

EDIT
I did find this, but it seems like there has to be a better way.

vaultah's user avatar

19 Answers 19

The map -oriented solution actually comes out ahead on my box — you definitely should not use sum for things that might be large numbers:

Timeit Comparison

Just for completeness, here’s a variant that uses print() (works on Python 2.6-3.x):

Time performance of different solutions

I’ve measured performance of @cdleary’s functions. The results are slightly different.

Each function tested with the input list generated by:

You may supply your own function via —sequence-creator=yourmodule.yourfunction command-line argument (see below).

The fastest functions for a given number of integers in a list ( len(nums) == digit_count ) are:

len(nums) in 1..30

len(nums) in 30..1000

Figure: N = 1000

Figure: N = 1000_000

To plot the first figure download cdleary.py and make-figures.py and run ( numpy and matplotlib must be installed to plot):

A one-liner without needing to cast to and from str

Simon Fromme's user avatar

This method works in 2.x as long as each element in the list is only a single digit. But you shouldn’t actually use this. It’s horrible.

Using a generator expression:

if the list contains only integer:

aflaisler's user avatar

This seems pretty clean, to me.

I found some examples are not compatible with python 3 I test one from @Triptych

s = filter(str.isdigit, repr(numList)) num = int(s)

in python 3 it’s gonna give error

TypeError: int() argument must be a string, a bytes-like object or a number, not ‘filter’

i think the more simple and compatible way would be

This may be helpful

If you happen to be using numpy (with import numpy as np ):

I think this seems to be the simplest solution with no need for any fcn

NOTE: This implementation is in Python 3

Dharman's user avatar

Abdelrahman Emam's user avatar

I found this thread while trying to convert a list to the real value of the underlying int in terms of a C-style pointer, but none of the other answers appear to work for this case. I think the following solution works as intended and could be useful to others even though it doesn’t necessarily answer the original question.

How to convert a float array to an integer array in python ?

Examples of how to convert a float array to an integer array in python:

Table of contents

Using the numpy function astype

To convert a float array to an integer array in python, a solution is to use astype, example:

Round the numbers before converting them in integer

It is also possible to round the numbers and after convert them to integer using the numpy function around

Note: work also with the function rint, example

Truncate the numbers first

Round to the nearest bigger integer

Round to the nearest smaller integer

References

Links Site
astype docs.scipy.org
around scipy doc
rint doc scipy
trunc doc scipy
ceil doc scipy
floor doc scipy
How to convert 2D float numpy array to 2D int numpy array? stackoverflow
Rounding scipy doc
Better rounding in Python’s NumPy.around: Rounding NumPy Arrays stackoverflow
are numpy array elements rounded automatically? stackoverflow

Author profile-image

Benjamin

Greetings, I am Ben! I completed my PhD in Atmospheric Science from the University of Lille, France. Subsequently, for 12 years I was employed at NASA as a Research Scientist focusing on Earth remote sensing. Presently, I work with NOAA concentrating on satellite-based Active Fire detection. Python, Machine Learning and Open Science are special areas of interest to me.

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

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