Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Find a Partial String in a Python List?

#1
How to Find a Partial String in a Python List?

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;665034&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<h2>Problem Formulation</h2>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Challenge</strong>: Given a Python list of strings and a query string. Find the strings that partially match the query string. </p>
<p>Example 1:</p>
<ul>
<li><strong>Input</strong>: <code>['hello', 'world', 'python']</code> and <code>'pyth'</code></li>
<li><strong>Output</strong>: <code>['python']</code></li>
</ul>
<p>Example 2: </p>
<ul>
<li><strong>Input</strong>: <code>['aaa', 'aa', 'a']</code> and <code>'a'</code></li>
<li><strong>Output</strong>: <code>['aaa', 'aa', 'a']</code></li>
</ul>
<p>Example 3: </p>
<ul>
<li><strong>Input</strong>: <code>['aaa', 'aa', 'a']</code> and <code>'b'</code></li>
<li><strong>Output</strong>: <code>[]</code></li>
</ul>
<p>Let’s dive into several methods that solve this and similar type of problems. We start with the most straightforward solution.</p>
<h2>Method 1: Membership + List Comprehension</h2>
<p class="has-global-color-8-background-color has-background">The most Pythonic way to find a list of partial matches of a given string <code>query</code> in a string list <code>lst</code> is to use the membership operator <code>in</code> and the list comprehension statement like so: <code>[s for s in lst if query in s]</code>.</p>
<p>Here’s a simple example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def partial(lst, query): return [s for s in lst if query in s] # Example 1:
print(partial(['hello', 'world', 'python'], 'pyth'))
# ['python'] # Example 2:
print(partial(['aaa', 'aa', 'a'], 'a'))
# ['aaa', 'aa', 'a'] # Example 3:
print(partial(['aaa', 'aa', 'a'], 'b'))
# []
</pre>
<p>In case you need some background information, feel free to check out our two tutorials and the referenced videos.</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/list-comprehension/" data-type="post" data-id="1171" target="_blank" rel="noreferrer noopener">List Comprehension in Python</a></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-find-a-partial-string-in-a-python-list/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9qsq2Vf48W8%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/python-membership-in-operator/" data-type="post" data-id="34005" target="_blank" rel="noreferrer noopener">The Membership Operator in Python</a></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-find-a-partial-string-in-a-python-list/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoQkfuBAk9lo%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<h2>Method 2: list() and filter()</h2>
<p class="has-global-color-8-background-color has-background">To find a list of partial query matches given a string list <code>lst</code>, combine the <a href="https://blog.finxter.com/python-membership-in-operator/" data-type="post" data-id="34005" target="_blank" rel="noreferrer noopener">membership operator</a> with the <code><a href="https://blog.finxter.com/python-filter/" data-type="post" data-id="22487" target="_blank" rel="noreferrer noopener">filter()</a></code> function in which you pass a <a href="https://blog.finxter.com/how-to-filter-in-python-using-lambda-functions/" data-type="post" data-id="2976" target="_blank" rel="noreferrer noopener">lambda function</a> that evaluates the membership operation for each element in the <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">list</a> like so: <code>list(filter(lambda x: query in x, lst))</code>.</p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def partial(lst, query): return list(filter(lambda x: query in x, lst)) # Example 1:
print(partial(['hello', 'world', 'python'], 'pyth'))
# ['python'] # Example 2:
print(partial(['aaa', 'aa', 'a'], 'a'))
# ['aaa', 'aa', 'a'] # Example 3:
print(partial(['aaa', 'aa', 'a'], 'b'))
# []
</pre>
<p>Beautiful <a rel="noreferrer noopener" href="https://blog.finxter.com/python-one-line-x/" data-type="post" data-id="10612" target="_blank">Python one-liner</a>, isn’t it? <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f984.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>I recommend you check out the following tutorial with video to shed some light on the background information here:</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/python-filter/" data-type="post" data-id="22487" target="_blank" rel="noreferrer noopener">Python Filtering</a></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-find-a-partial-string-in-a-python-list/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3nG4TLkqzf8%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<p>Generally, I like list comprehension more than the <code>filter()</code> function because the former is more concise (e.g., no need to <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list/" data-type="post" data-id="21502" target="_blank">convert</a> the result to a list) and slightly faster. But both work perfectly fine!</p>
<h2>Method 3: Regex Match + List Comprehension</h2>
<p class="has-global-color-8-background-color has-background">The most flexible way to find a list of partial query matches given a string list <code>lst</code> is provided by Python’s powerful <a rel="noreferrer noopener" href="https://blog.finxter.com/python-regex/" data-type="post" data-id="6210" target="_blank">regular expressions</a> functionality. For example, the expression <code>[x for x in lst if re.match(pattern, x)]</code> finds all strings that match a certain query pattern as defined by you.</p>
<p>The following examples showcase this solution:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1,4,5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import re def partial(lst, query): pattern = '.*' + query + '.*' return [x for x in lst if re.match(pattern, x)] # Example 1:
print(partial(['hello', 'world', 'python'], 'pyth'))
# ['python'] # Example 2:
print(partial(['aaa', 'aa', 'a'], 'a'))
# ['aaa', 'aa', 'a'] # Example 3:
print(partial(['aaa', 'aa', 'a'], 'b'))
# []
</pre>
<p>In this example, we use the dummy pattern <code>.*query.*</code> that simply matches words that contain the <code>query</code> string. However, you could also do more advanced pattern matching—regex to the rescue!</p>
<p>Again, I’d recommend you check out the background info on regular expressions:</p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/python-regex-match/" data-type="post" data-id="5759" target="_blank" rel="noreferrer noopener">Python Regex <code>match()</code> — A Simple Illustrated Guide</a></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-find-a-partial-string-in-a-python-list/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5d3vQ8N0MJg%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<h2>Regex Humor</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2022/06/image-133.png" alt="" class="wp-image-428862" width="700" height="629" srcset="https://blog.finxter.com/wp-content/uploads/2022/06/image-133.png 785w, https://blog.finxter.com/wp-content/uplo...00x270.png 300w, https://blog.finxter.com/wp-content/uplo...68x691.png 768w" sizes="(max-width: 700px) 100vw, 700px" /><figcaption><em>Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee.</em> (<a href="https://imgs.xkcd.com/comics/regular_expressions.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/regular_expressions.png" target="_blank" rel="noreferrer noopener">source</a>)</figcaption></figure>
</div>
</div>


https://www.sickgaming.net/blog/2022/09/...thon-list/
Reply



Forum Jump:


Users browsing this thread:
3 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016