将print语句与python中的列表理解相结合

时间:2013-03-28 08:44:26

标签: python printing list-comprehension polling

我正在编写代码,使用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!"

如何将print语句与上述组合?

1 个答案:

答案 0 :(得分:3)

使用正常的for循环,可以这样做:

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它。


作为旁注,hacky解决方案:

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]

但这是非常非语言 - 请改用其他版本。