Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Join List Pairs

#1
Python Join List Pairs

<div><p class="has-background has-luminous-vivid-amber-background-color"><strong>Given a list of strings. Join the first with the second string, the second with the third, and so on. The one-liner <code>[lst[i] + lst[i+1] for i in range(0, len(lst), 2)]</code> solves the problem by using the range function to iterate over every other index <code>i=0, 2, 4, 5, ...</code> to concatenate the <code>i</code>-th and the <code>i+1</code>-th elements in a list comprehension expression with <code>lst[i] + lst[i+1]</code>.</strong></p>
<p>You may already know the normal <a href="https://blog.finxter.com/python-join-list/" target="_blank" rel="noreferrer noopener">join function</a> in Python:</p>
<h2>Intro: Python Join</h2>
<p><strong>Problem</strong>: Given a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">list </a>of elements. How to join the elements by <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">concatenating</a> all elements in the list?</p>
<p><strong>Example</strong>: You want to <a href="https://blog.finxter.com/python-list-to-string/" target="_blank" rel="noreferrer noopener">convert list</a> <code>['learn ', 'python ', 'fast']</code> to the string <code>'learn python fast'</code>. </p>
<p><strong>Quick Solution</strong>: to convert a list of strings to a string, do the following.</p>
<ul>
<li>Call the <code>''.join(list)</code> method on the empty string <code>''</code> that glues together all strings in the <code>list</code> and returns a new string. </li>
<li>The string on which you call the join method is used as a delimiter between the list elements. </li>
<li>If you don’t need a delimiter, just use the empty string <code>''</code>. </li>
</ul>
<p><strong>Code</strong>: Let’s have a look at the 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="">lst = ['learn ', 'python ', 'fast']
print(''.join(lst))</pre>
<p>The output 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="">learn python fast</pre>
<p>However, what if you want to do something different. Rather than joining all strings in the list to a single string, you want to join the strings in the list in pairs.</p>
<h2>Problem: Python Join List Pairs</h2>
<p><strong>Problem</strong>: Given a list of strings. Join the first with the second string, the second with the third, and so on. </p>
<p><strong>Example</strong>: Let’s consider the following minimal example:</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="">['x', 'y', 'v', 'w']</pre>
<p>Is there any simple way to pair the first with the second and the third with the fourth string to obtain the following output?</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="">['xy', 'vw']</pre>
<p>Note that the length of the strings in the list is variable so the following would be a perfectly acceptable input:</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="">['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff'] </pre>
<p>You can play with all three methods before diving into each of them:</p>
<p> <iframe src="https://trinket.io/embed/python/1a68a6e75f" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: What’s the most Pythonic method?</em></p>
<h2>Method 1: Zip() + List Comprehension</h2>
<p>You can use the following smart one-liner solution</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="">lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']
out = [x + y for x,y in zip(lst[::2], lst[1::2])]
print(out)
# ['aaaab', 'ccdddd', 'eeefff']</pre>
<p>The one-liner uses the following strategy:</p>
<ul>
<li>Obtain two slices <code>lst[::2]</code> and <code>lst[1::2]</code> of the original list over every other element starting from the first and the second elements, respectively. If you need to refresh your slicing skills, <a rel="noreferrer noopener" href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank">check out my detailed blog article.</a></li>
<li>Zip the two slices to a sequence of tuples using the <code>zip(...)</code> function. This aligns the first with the second elements from the original list, the third with the forth, and so on. To refresh your <code>zip()</code> skills, <a rel="noreferrer noopener" href="https://blog.finxter.com/zip-unzip-python/" target="_blank">check out my blog tutorial here.</a></li>
<li>Use list comprehension to iterate over each pair of values <code>x,y</code> and concatenate them using list concatenation <code>x+y</code>. For a refresher on list comprehension, <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">check out this free tutorial</a>—and for a refresher on list concatenation, <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">check out this one</a>.</li>
</ul>
<h2>Method 2: Iterator + List Comprehension</h2>
<p>You can also use an iterator to accomplish this:</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="">lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']
it = iter(lst)
out = [x + next(it, '') for x in it] print(out)
# ['aaaab', 'ccdddd', 'eeefff']</pre>
<p>Here’s the idea:</p>
<ul>
<li>Create an iterator object it using the built-in function <code>iter()</code>.</li>
<li>Use list comprehension to go over each element in the iterator.</li>
<li>Concatenate each element with the return value of calling the <code>next()</code> function on the iterator. This ensures that the iterator moves one position further iterating over the list. So, the next element <code>x</code> won’t be a duplicate.</li>
</ul>
<h2>Method 3: Use List Comprehension with Indexing</h2>
<p>This method is the most straightforward one for Python beginners:</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="">lst = ['aaaa', 'b', 'cc', 'dddd', 'eee', 'fff']
out = [lst[i] + lst[i+1] for i in range(0, len(lst), 2)]
print(out)
# ['aaaab', 'ccdddd', 'eeefff']</pre>
<p>The idea is simply to use the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-join-list-range-a-helpful-guide/" target="_blank">range </a>function to iterate over every other index <code>i=0, 2, 4, 5, ...</code> to access the <code>i</code>-th and the <code>i+1</code>-th elements at the same time in the <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">expression statement of list comprehension</a> (to <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-concatenation-add-vs-inplace-add-vs-extend/" target="_blank">concatenate </a>those with <code>lst[i] + lst[i+1]</code>). </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/06/...ist-pairs/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016