在python中有用的列表理解吗?

时间:2018-05-24 02:51:18

标签: python regex list-comprehension pyserial

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循环代码? 请分享您的意见。 :)谢谢你的阅读。

2 个答案:

答案 0 :(得分:1)

我会使用for循环,只是因为您可以在找到唯一设备后提前停止迭代。

for n in listport.comports():
    if re.findall(regex_vplogVID, n.hwid):
        vplogserial = ser.Serial(n.device)
        break

答案 1 :(得分:1)

如果确实只有一场比赛,请不要使用列表理解。相反,使用普通的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])