<p>我有多个字符串,如下所示:</p>
<pre><code>“BPBA-SG790-NGTP-W-AU-BUN-3Y”
</code></pre>
<p>我想将字符串与列表进行比较,如果字符串的一部分在列表中,我只想将列表中找到的部分作为新变量</p>
<p>这是我的代码:</p>
<pre><code> mylist = ["770", "790", "1470", "1490"]
sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”
matching = [s for s in mylist if any(xs in s for xs in sq)]
print(matching)
>>> ['770', '790', '1470', '1490']
</code></pre>
<p>例如,这就是我想要得到的:</p>
<pre><code> mylist = ["770", "790", "1470", "1490"]
sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”
matching = [s for s in mylist if any(xs in s for xs in sq)]
print(matching)
>>> 790
</code></pre>
<p>你知道怎么做吗</p>
<p>这样,您可以使用列表理解:</p>
<pre><code>mylist = ["770", "790", "1470", "1490"]
sq = "BPBA-SG790-NGTP-W-AU-BUN-3Y"
matching = [m for m in mylist if m in sq]
print(matching)
</code></pre>
<p>输出:</p>
<pre><code>['790']
</code></pre>