擅长:python、mysql、java
<p>如果确实只有一个匹配项,不要使用列表。相反,在找到匹配项后使用普通for循环和break:这样就可以保证只有一个匹配项:</p>
<pre><code># I want to find COM port by using specific hwid
regex_vplogVID = re.compile(r'{\S+}_VID')
port_device = None
for port in listport.comports():
if re.findall(regex_vplogVID, port.hwid):
port_device = port.device
break
</code></pre>
<hr/>
<p>额外的好处:如果你想超越这一点,如果没有匹配的话,你可以使用for else习语,但这是一个不太常用的习语,经常会让人困惑:</p>
<pre><code># I want to find COM port by using specific hwid
regex_vplogVID = re.compile(r'{\S+}_VID')
for port in listport.comports():
if re.findall(regex_vplogVID, port.hwid):
port_device = port.device
break
else: # no break encountered
raise ValueError("COM port not found")
# No need now to have a default of `None` and check for it
vplogserial = ser.Serial(port_device[0])
</code></pre>