Sick Gaming
[Tut] How to Convert a Float List to an Integer List in Python - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] How to Convert a Float List to an Integer List in Python (/thread-98213.html)



[Tut] How to Convert a Float List to an Integer List in Python - xSicKxBot - 11-11-2020

How to Convert a Float List to an Integer List in Python

<div><p class="has-pale-cyan-blue-background-color has-background">The most Pythonic way to convert a list of floats <code>fs</code> to a list of integers is to use the one-liner <code>fs = [int(x) for x in fs]</code>. It iterates over all elements in the list <code>fs</code> using list comprehension and converts each list element <code>x</code> to an integer value using the <code>int(x)</code> constructor. </p>
<p>This article shows you the simplest ways to <strong>convert a one-dimensional <a href="https://blog.finxter.com/python-lists/" title="The Ultimate Guide to Python Lists" target="_blank" rel="noreferrer noopener">list </a>consisting only of floats to a list of int</strong>.</p>
<p><strong>Problem</strong>: Given a list of floats <code>[1.0, 2.0, 3.0]</code>. How to convert it to a list of ints <code>[1, 2, 3]</code>?</p>
<p>The methods are not applicable to <a href="https://blog.finxter.com/python-list-of-lists/" target="_blank" rel="noreferrer noopener" title="Python List of Lists – A Helpful Illustrated Guide to Nested Lists in Python">lists of lists</a>, they contain rounding errors that are different in each method. If necessary, you can add cycles or define custom functions to check, account for and minimize errors.</p>
<h2>Method 1: List Comprehension</h2>
<p>Suppose we have a list:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a = [1.1, 1.2, 1.8, 0.5, 5.9, -2.3]</pre>
<p>Now, check the type of the list numbers:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(type(a[0]))
# &lt;class 'float'>
</pre>
<p>Let’s apply the built-in function <em><code>int</code></em>, and get a list of integers:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print([int(a) for a in a])
# [1, 1, 1, 0, 5, -2]
</pre>
<p>Check the type of numbers in the new list:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">A = [int(a) for a in a]
print(type(A[0]))
# &lt;class ‘int’>
</pre>
<p>Thus, using the built-in function <em><code>int</code></em>, which converts a real number rounds towards zero, or rather, it discards the fractional part, we can get a new list of integers with a <a href="https://blog.finxter.com/python-one-line-x/" target="_blank" rel="noreferrer noopener" title="Python One Line X">one-line code</a>.</p>
<h2>Method 2: Map Function</h2>
<p>The built-in function <code><a href="https://blog.finxter.com/daily-python-puzzle-string-encrpytion-ord-function-map-function/" title="Mastering the Python Map Function [+Video]" target="_blank" rel="noreferrer noopener">map</a></code> is well optimized and efficient, when it is called, the elements of the list are retrieved upon access. Therefore, one element is stored and processed in memory, which allows the program not to store the entire list of elements in the system memory.</p>
<p>Apply to the same list <code>a</code> the following code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(list(map(int, a)))
# [1, 1, 1, 0, 5, -2]
</pre>
<p>It makes no sense to check the type of the elements of the resulting list, since when we called the <code>map</code> function, we passed the <code>int</code> function already described in method 1 as an argument, and wrapped the result in a list using the <code data-enlighter-language="generic" class="EnlighterJSRAW">list</code> function.</p>
<p>The quality of this transformation of the list, or rather the rounding error, is the same as in the first method.</p>
<h2>Method 3: Round &amp; List Comprehension</h2>
<p>It is very similar to the first, but unlike <code>int</code>, it doesn’t just discard the fractional part but rounds to the nearest even integer if the fractional part is 0.5. You can also pass as the second argument the number of decimal places to which rounding is required, by default it is 0, this is what we will use:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print([round(a) for a in a])</pre>
<p>Check the type of numbers in the new list:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">D = [round(a) for a in a]
print(type(D[0]))
# &lt;class ‘int’>
</pre>
<p>As you can see from this example, there are different built-in functions to achieve our goal, the difference is in the method and the magnitude of the <a href="https://blog.finxter.com/decimal-pythons-float-trap-and-how-to-solve-it/" target="_blank" rel="noreferrer noopener" title="Decimal: Python’s Float Trap and How to Solve it">rounding error</a>.</p>
<h2>Method 4: Math Module</h2>
<p>In this way, I suggest using the imported module <code><a href="https://blog.finxter.com/python-math-module/" title="Python Math Module [Ultimate Guide]" target="_blank" rel="noreferrer noopener">math</a></code>, in which we will use the three functions <code>ceil()</code>, <code>floor()</code>, and <code>trunc()</code>. let’s take a closer look at each. They have the same syntax, the difference is in the way of rounding.</p>
<p>Let’s apply to the original list:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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]
</pre>
<p>‘Ceil’ rounds to the next largest integer, respecting the sign(<strong><em>-2.3 &lt; -2 which is True</em></strong>).</p>
<p>Check the type of numbers in the new list:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">C = [math.ceil(a) for a in a]
print(type(C[0]))
# &lt;class ‘int’>
</pre>
<p>Consider the following function in the ‘math’ – ‘floor’ module, which is the opposite of ‘ceil’ – rounding down to the nearest integer:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print([math.floor(a) for a in a])
# [1, 1, 1, 0, 5, -3]
</pre>
<p>Check the type:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">F = [math.floor(a) for a in a]
print(type(F[0]))
# &lt;class ‘int’>
</pre>
<p>The next function, <code>trunc()</code>, is analogous to the built-in function <code>int()</code> — it simply discards the fractional part whatever it is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print([math.trunc(a) for a in a])
# [1, 1, 1, 0, 5, -2]</pre>
<p>And check the type:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">T = [math.trunc(a) for a in a]
print(type(T[0]))
# &lt;class ‘int’></pre>
<h2>Method 5: NumPy</h2>
<p>Here’s a look at converting a list from an <code>int</code> to an array using the <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener" title="NumPy Tutorial – Everything You Need to Know to Get Started">NumPy </a>module. The difference between an array and a list is that all elements of an array must be of the same type, like “float” and “int”. Numeric operations with large amounts of data can be performed with arrays much faster and more efficiently than with lists.</p>
<p>Let’s turn our first list <code>a</code> into an array:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
N = np.array(a, int)
</pre>
<p>We pass two arguments to the array function, the name of the list to convert to an array and the type for each element.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># [ 1 1 1 0 5 -2]</pre>
<p>Сheck the type of elements:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(type(N[0]))
# &lt;class 'numpy.int32'>
</pre>
<p>Unlike the <code>int</code> number type in Python, the NumPy module defines them slightly differently and is divided into several subgroups. For example, <code>'int32'</code> are integers ranging from -2147483648 to 2147483647 (4-byte numbers), <code>'int64'</code> are numbers from -9223372036854775808 to 9223372036854775807 (8-byte numbers), there are also different types of <code>'int'</code> for 32- and 64-bit operating systems, this must be taken into account when calculating with arrays.</p>
</p>
<p>The post <a href="https://blog.finxter.com/how-to-convert-a-float-list-to-an-integer-list-in-python/" target="_blank" rel="noopener noreferrer">How to Convert a Float List to an Integer List in Python</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/11/10/how-to-convert-a-float-list-to-an-integer-list-in-python/