python 中的列表理解有用吗?
Is it useful list comprehension in python?
import serial as ser
import serial.tools.list_ports as listport
import re
try:
# VID regex
regex_vplogVID = re.compile(r'{\S+}_VID')
# I want to find COM port by using specific hwid
port_device = [n.device for n in listport.comports() if re.findall(regex_vplogVID, n.hwid)]
vplogserial = ser.Serial(port_device[0])
except Exception as e:
print(e)
实际上,我是使用 python 的新手程序员。
我想使用唯一的 hwid 查找端口,但我认为列表理解不正确,因为端口将只返回一个。
我是否只使用了 for 循环代码?
请分享您的意见。 :) 感谢您的阅读。
我会使用 for
循环,如果只是因为一旦找到唯一设备就可以提前停止迭代。
for n in listport.comports():
if re.findall(regex_vplogVID, n.hwid):
vplogserial = ser.Serial(n.device)
break
如果确实只有一个匹配项,请不要使用列表理解。相反,使用普通的 for 循环并在找到匹配项后中断:那么你保证只有一个匹配项:
# 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
奖金:如果你想超越那个,你可以在没有匹配的情况下使用 for-else 习语,但这是一个不太常用的习语,并且经常让人感到困惑:
# 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])
import serial as ser
import serial.tools.list_ports as listport
import re
try:
# VID regex
regex_vplogVID = re.compile(r'{\S+}_VID')
# I want to find COM port by using specific hwid
port_device = [n.device for n in listport.comports() if re.findall(regex_vplogVID, n.hwid)]
vplogserial = ser.Serial(port_device[0])
except Exception as e:
print(e)
实际上,我是使用 python 的新手程序员。 我想使用唯一的 hwid 查找端口,但我认为列表理解不正确,因为端口将只返回一个。
我是否只使用了 for 循环代码? 请分享您的意见。 :) 感谢您的阅读。
我会使用 for
循环,如果只是因为一旦找到唯一设备就可以提前停止迭代。
for n in listport.comports():
if re.findall(regex_vplogVID, n.hwid):
vplogserial = ser.Serial(n.device)
break
如果确实只有一个匹配项,请不要使用列表理解。相反,使用普通的 for 循环并在找到匹配项后中断:那么你保证只有一个匹配项:
# 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
奖金:如果你想超越那个,你可以在没有匹配的情况下使用 for-else 习语,但这是一个不太常用的习语,并且经常让人感到困惑:
# 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])