2013-01-22 45 views
2

我確定它已被問及它會得到一個「只使用生成器理解!」響應,但以防萬一它是在標準庫中的某個地方,我只是無法找到它在itertools ...帶有else子句的過濾器(numpy.where)

在Python 3.x中,有一個功能選擇:

(x if c else y for c, x, y in zip(cs, xs, ys)) 

對於例如,numpy.where(cs, xs, ys)完全是這樣。

+0

'numpy.where(cs,xs,ys)'有什麼問題?如果它不是標準語言,請使用適當的庫或者編寫您提出的方法。 – eumiro

回答

2

這是一個生成器表達式,所以才解開它:

cs = [True, False, True] 
xs = [1, 2, 3] 
ys = [10, 20, 30] 

def generator(cs, xs, ys): 
    for c, x, y in zip(cs, xs, ys): 
     yield x if c else y 

print(list(x if c else y for c, x, y in zip(cs, xs, ys))) 
print(list(generator(cs, xs, ys))) 

輸出:

[1, 20, 3] 
[1, 20, 3] 
+0

爲了我自己的利益:在for語句中使用zip和itertools.izip有區別嗎? – BenDundee

+0

在Python 3中,我不能(也不需要)使用它。在Python 2中,'ixip()'就像'zip()',只不過它返回一個迭代器而不是一個列表。它已經在Python 3的'itertools'中消失了,因爲這是該版本中的'zip()'所具有的功能。技術上迭代器對象是生成器對象。我沒有提到所有這些,因爲你的問題有'python-3.x'標籤, – martineau

1

嗯,這樣的事情呢? (我在Python 2.7.3,但我不認爲在這裏事項)

>>> import itertools as it 
>>> a=[1,2,3] 
>>> b=[10,20,30] 
>>> cond=[True, False, True] 
>>> func=lambda c,x,y: x if c else y 
>>> test=it.starmap(func, it.izip(cond,a,b)) 
>>> test.next() 
1 
>>> test.next() 
20 
>>> test.next() 
3