Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Tuple to Integer

#1
Python Tuple to Integer

<div><p>You have a tuple of integers—but you want a single integer. What can you do?</p>
<p><strong>Problem</strong>: Given a tuple of values.</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 = (1, 2, 3)</pre>
<p>Your goal is to convert it to a single integer value.</p>
<p>There are multiple ways of accomplishing this (dependent on what exactly you want to do). Let’s get a quick overview in our interactive Python shell:</p>
<p> <iframe src="https://trinket.io/embed/python/bf5faba68b" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Modify method 2 to calculate the average and round to the next integer!</em></p>
<p>Let’s dive into each of the method.</p>
<h2>Method 1: sum()</h2>
<p>The first way of converting a tuple to an integer, simply sum up all values. The <code>sum()</code> function is built-in in Python and you can use it on any iterable:</p>
<p><strong>The syntax is <code>sum(iterable, start=0)</code>:</strong></p>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>iterable</code></td>
<td>Sum over all elements in the <code>iterable</code>. This can be a list, a tuple, a set, or any other data structure that allows you to iterate over the elements. <br /><strong>Example</strong>: <code>sum([1, 2, 3])</code> returns <code>1+2+3=6</code>. </td>
</tr>
<tr>
<td><code>start</code></td>
<td>(Optional.) The default start value is 0. If you define another start value, the sum of all values in the <code>iterable</code> will be added to this start value. <br /><strong>Example</strong>: <code>sum([1, 2, 3], 9)</code> returns <code>9+1+2+3=15</code>.</td>
</tr>
</tbody>
</table>
</figure>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python sum() List - A Simple Illustrated Guide" width="1400" height="788" src="https://www.youtube.com/embed/BGddaP8pNcc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>Here’s how you can use the <code>sum()</code> function to sum over all values in an iterable (such as a tuple):</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="">
# Method 1: sum()
t = (1, 2, 3)
i = sum(t)
print(i)
# 6</pre>
<p>In this case, it calculates 1+2+3=6. You can learn more about the <code>sum()</code> function <a href="https://blog.finxter.com/python-sum-list/" title="Python sum() List – A Simple Illustrated Guide" target="_blank" rel="noreferrer noopener">on this Finxter blog article</a>.</p>
<p>But what if you want to use all tuple values as digits of a larger integer value?</p>
<h2>Method 2: str() + list comprehension + join()</h2>
<p><a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">List comprehension</a> is a compact way of creating lists. The simple formula is <code>[expression + context]</code>.</p>
<ul>
<li><strong>Expression</strong>: What to do with each list element?</li>
<li><strong>Context</strong>: What elements to select? The context consists of an arbitrary number of <code>for</code> and <code>if</code> statements.</li>
</ul>
<p>You can use it in combination with the <code>sum()</code> function to calculate the integer 123 from the tuple (1, 2, 3)—by using the tuple values as digits of the larger 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="">
# Method 2: str() + list comprehension + join()
t = (1, 2, 3)
i = ''.join(str(x) for x in t)
print(int(i))
# 123</pre>
<p>Well, to be frank, we didn’t even use list comprehension here—the correct term for <code>str(x) for x in t</code> is “generator expression”. The difference to list comprehension is that it creates a generator instead of a list. </p>
<p>If you like functional programming, you may like the following method: </p>
<h2>Method 3: str() + map() + join()</h2>
<p>The map() function creates a new iterable from an iterable by applying a function to each element of the original iterable:</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Mastering the Python Map Function [+Video]" width="1400" height="788" src="https://www.youtube.com/embed/tqph6mWC3m8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>You can pass the <code><a href="https://blog.finxter.com/python-list-to-string/" title="Python List to String: A Helpful Guide with Interactive Shell">str()</a></code> function into the <code><a href="https://blog.finxter.com/how-to-get-rid-of-pythons-map-function-with-list-comprehension/" title="How to Get Rid of Python’s Map Function With List Comprehension">map()</a></code> function to convert each tuple element to a string.</p>
<p>Then, you can <a href="https://blog.finxter.com/python-join-list/" target="_blank" rel="noreferrer noopener" title="Python Join List [Ultimate Guide]">join </a>all strings together to a big string. After converting the big string to an integer, you’ve successfully merged all tuple integers to a big integer value.</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="">
# Method 3: str() + map() + join()
t = (1, 2, 3)
i = ''.join(map(str, t))
print(i)
# 123</pre>
<p>There are many details to the <code>string.join()</code> method. <a href="https://blog.finxter.com/python-join-list/" target="_blank" rel="noreferrer noopener" title="Python Join List [Ultimate Guide]">You can read the detailed tutorial on the Finxter blog.</a> Here’s the short version:</p>
<p>The <code>string.join(iterable)</code> method concatenates all the string elements in the <code>iterable</code> (such as a list, string, or tuple) and returns the result as a new string. The <code>string</code> on which you call it is the delimiter string—and it separates the individual elements. For example, <code>'-'.join(['hello', 'world'])</code> returns the joined string <code>'hello-world'</code>.</p>
<h2>Method 4: Multiple Assignments</h2>
<p>If you simply want to get multiple integers by assigning the individual tuple values to integer variables, just use the <a href="https://blog.finxter.com/the-top-18-best-python-tricks/" target="_blank" rel="noreferrer noopener" title="Top 18 Cool Python Tricks">multiple assignment</a> feature:</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="">
# Method 4: multiple assignments
t = (1, 2, 3)
a, b, c = t
print(a)
print(b)
print© '''
1
2
3 '''
</pre>
<p>Variables <code>a</code>, <code>b</code>, and <code>c</code> have the values 1, 2, and 3, respectively.</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


https://www.sickgaming.net/blog/2020/07/...o-integer/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016