我有这段代码,我有一个布尔值列表(名为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中有更简洁的方法。
有什么建议吗?
答案 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)]