Python 使用布尔列表作为掩码
我有一段代码,其中我有一个布尔值列表(名为Python 使用布尔列表作为掩码,python,python-2.7,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 ho
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”前缀。我相信在python中有一种更干净的方法可以做到这一点
有什么建议吗?您可以在列表理解中使用:
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)]
您可以与列表理解一起使用:
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)]
您可以使用一个奇特的技巧将其缩短:
["not " * (1 - x) + y.obj_dict['self'].get_topic() for x,y in zip(comb, self.parents)]
您可以使用一个奇特的技巧将其缩短:
["not " * (1 - x) + y.obj_dict['self'].get_topic() for x,y in zip(comb, self.parents)]
你可能想要
x[1]。
而不仅仅是x.
。你是说self.parents
?像这样:zip(comb,self.parents)
@pkacprzak谢谢,这可能就是我想要让助教不检查这个代码的原因:)@ReutSharabani:不要实际使用'not'*(1-x[0])
@ReutSharabani:因为它不可读。如果您坚持要将可读性抛出窗口,至少要做到'not'*(not x[0])
。代码越短并不一定越好。你可能想要x[1]。
而不仅仅是x.
。你是说self.parents
?像这样:zip(comb,self.parents)
@pkacprzak谢谢,这可能就是我想要让助教不检查这个代码的原因:)@ReutSharabani:不要实际使用'not'*(1-x[0])
@ReutSharabani:因为它不可读。如果您坚持要将可读性抛出窗口,至少要做到'not'*(not x[0])
。代码越短并不一定越好。如果除了这个zip
,你永远不需要主题,我会把它做成genexprs而不是listcomp。但除此之外,可读性很好,仍然很简洁。@abarnert不是个好主意!谢谢如果除了这个zip
,你永远不需要主题,我会把它做成genexprs而不是listcomp。但除此之外,可读性很好,仍然很简洁。@abarnert不是个好主意!谢谢