我正在编写使用GSM调制解调器用python发送和接收消息的代码。
每当接收到新消息时,从串行端口对象读取后,我在列表x中得到以下响应。
+CMTI: "SM",0 # Message notification with index
我正在为这个指示进行投票,我已经使用列表理解来检查我是否收到了上面的响应
def poll(x):
regex=re.compile("\+CMTI:.......")
[m for l in x for m in [regex.search(l)] if m]
这似乎是可行的,但是我想添加一个print语句,只要找到匹配的
print "You have received a new message!"
如何将打印报表与上述内容结合起来?
最佳答案
对于normalfor
循环,可以这样做:
def poll(x):
regex = re.compile("\+CMTI:.......")
lst = []
for l in x:
for m in [regex.search(l)]:
if m:
lst.append(m)
print "You have received a new message!"
注意,这个列表没有被存储在任何地方(在函数作用域之外)——也许您想
return
它。顺便说一句,老套的解决方案是:
from __future__ import print_function
def poll(x):
regex = re.compile("\+CMTI:.......")
[(m, print("You have received a new message!"))[0] for l in x for m in [regex.search(l)] if m]
但这是非常不通俗的-用另一个版本代替。
关于python - 在python中将打印语句与列表理解结合在一起,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15677429/