[英]Conditional itertools.product
假設我有一個重物列表,為了論證考慮x = numpy.arange(10)/10
我通過gen = itertools.product(x,x)
創建了一個生成器來執行一些計算。 事實是我的計算是對稱的:對於所有i
和j
,重heavy_calc(x[i],x[j]) = heavy_calc(x[j],x[i])
。
因此,我只想計算矩陣的上半部分。 僅當i >= j
(x[i], x[j])
我如何才能使生成器返回(x[i], x[j])
?
我會手工構建生成器:
def gen(x):
for i in range(len(x)):
for y in x[i:]:
yield(x[i], y)
它按預期提供:
>>> list(gen(list(range(4))))
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
使用itertools.combinations_with_replacement
,而不是product
:
gen = itertools.combinations_with_replacement(x, 2)
請注意,這給出了(x[i], x[j])
元組,其中i <= j
,而不是i >= j
。 這對於您的用例應該沒問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.