我有 MNEA 0183 消息,例如:
MNEAMessages = [
"$GPGGA, 3555.1581, E, 1248.5819, W, 768.1, M",
"$GLGGA, 3555.1581, E, 1248.5819, W, 768.1, M",
"$GAGGA, 3555.1581, E, 1248.5819, W, 768.1, M",
"$BDGGA, 3555.1581, E, 1248.5819, W, 768.1, M",
"$GLRMC, 1, 2, 3, 4, 5, 6",
"$GARMC, 1, 2, 3, 4, 5, 6"
]
如您所见,我有以 $GPGGA、$GARMC 开头的消息。我的目标是查找并统计包含 $xxGGA 的消息。我编写了以下代码来执行此操作。
counterGGA = 0
for message in MNEAMessages:
startIndex = message.find("$")
if startIndex != -1 and (message[startIndex + 3 : startIndex + 6] == "GGA"):
# Oh yeah, it is a GGA message
counterGGA += 1
print(counterGGA) # This gives me the number 4 as I want.
我想知道是否有更短或更有效的方法来做到这一点。例如,像这样:
if message.find("$xxGGA"):
# Hell yeah, it is better way to find GGA messages.
counterGGA += 1
您可以使用
re.match
查找包含该模式的字符串,即生成器表达式中的列表循环
>>> import re
>>> sum(1 if re.match('\$[\w]{2}GGA', s) else 0 for s in MNEAMessages)
4