我確定它已被問及它會得到一個「只使用生成器理解!」響應,但以防萬一它是在標準庫中的某個地方,我只是無法找到它在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)
完全是這樣。
我確定它已被問及它會得到一個「只使用生成器理解!」響應,但以防萬一它是在標準庫中的某個地方,我只是無法找到它在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)
完全是這樣。
這是一個生成器表達式,所以才解開它:
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]
嗯,這樣的事情呢? (我在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
'numpy.where(cs,xs,ys)'有什麼問題?如果它不是標準語言,請使用適當的庫或者編寫您提出的方法。 – eumiro