使用布尔列表作为掩码

时间:2014-01-07 23:41:54

标签: python python-2.7

我有这段代码,我有一个布尔值列表(名为comb)和另一个列表中的一些对象(self.parents,总是大小相同),我想要相应地采取行动

这是当前的代码:

    # this is for the result
    parents_arr = []
    # 'comb' is an array of booleans - same size as 'self.parents'
    for i in range(len(comb)):
        # this decides how to act according to comb[i]
        if comb[i]:
            # add string from parent as is to list
            parents_arr.extend([self.parents[i].obj_dict['self'].get_topic()])
        else:
            # append 'not' to string from parent and addto list
            parents_arr.extend(["not %s" % self.parents[i].obj_dict['self'].get_topic()])

它的作用是,根据“mask”(布尔数组),它将“not”字符串作为前缀为false。我确信在python中有更简洁的方法。

有什么建议吗?

2 个答案:

答案 0 :(得分:4)

您可以将zip与列表理解结合使用:

topics = (x.obj_dict['self'].get_topic() for x in self.parents)
result = [x if y else "not %s" % x for x,y in zip(topics, comb)]

答案 1 :(得分:1)

你可以使用花哨的技巧来缩短它:

["not " * (1 - x) + y.obj_dict['self'].get_topic() for x,y in zip(comb, self.parents)]
相关问题