我有两个清单。例如:
a = [1,None,0,1,None,None]
b=[1,0,None,None,0,None]
a[i]
和b[i]
是相应的值。它们将是等价的(例如,其中i = 0),一个将包含一个值而另一个将是无(例如,i = 1)或两者都将是None(例如,i = 5)。我希望整理这些列表,以生成列表c
:
c = [1,0,0,1,0,None]
目前我这样做:
def combinePredictions (a,b):
#Naive method to combine lists. Assumes that the lists either have the same value or no value. Not for production use. Only use for testing.
i = 0
c = []
for each in range(len(a)):
if a[i] == b[i]:
c.append(a[i])
elif a[i] == None:
c.append(b[i])
elif b[i] == None:
c.append(a[i])
i = i +1
return c
如何更有效地完成这项工作?
答案 0 :(得分:4)
以下是我将如何迭代重构此代码
您不需要i
和each
的单独值。如果您在一个范围内进行迭代,那么手动递增索引并没有多大意义。
def combinePredictions (a,b):
c = []
for i in range(len(a)):
if a[i] == b[i]:
c.append(a[i])
elif a[i] == None:
c.append(b[i])
elif b[i] == None:
c.append(a[i])
return c
你可以减少条件数,因为你唯一没有附加[i]的时候就是没有条件:
def combinePredictions (a,b):
c = []
for i in range(len(a)):
if a[i] is None:
c.append(b[i])
else:
c.append(a[i])
return c
您可以使用zip
并行迭代两个列表,而无需参考其索引:
def combinePredictions (a,b):
c = []
for x,y, in zip(a,b):
if x is None:
c.append(y)
else:
c.append(x)
return c
这可能已经足够了,但是如果我们对减少行数(可以说是以可读性为代价)感兴趣,那就让我们走得更远。
您可以将该条件设置为表达式并将其内联到append
调用中:
def combinePredictions (a,b):
c = []
for x,y, in zip(a,b):
c.append(y if x is None else x)
return c
您可以将该循环变为列表理解:
def combinePredictions (a,b):
return [y if x is None else x for x,y in zip(a,b)]
答案 1 :(得分:0)
尝试列表理解:
a = [1,None,0,1,None,None]
b = [1,0,None,None,0,None]
print([1 if x == 1 or y == 1 else None if x == None and y == None else 0 for x, y in zip(a, b)])
# [1, 0, 0, 1, 0, None]
答案 2 :(得分:0)
a = [1, None, 0, 1, None, None]
b = [1, 0, None, None, 0, None]
zipped = [x if y is None else y for x, y in zip(a, b)]
for i in zipped:
print(i)
答案 3 :(得分:0)
我不知道这是否更有效,但你绝对可以让它变得更加抒情和可读:
y_true = [1, None, 0, None]
y_pred = [1, 0, 0, None]
collated = []
for true, predicted in zip(y_true, y_pred):
if predicted is None:
collated.append(true)
else:
collated.append(predicted)
print(collated) # [1, 0, 0, None]