迭代数组两次(笛卡尔积)但只考虑一半的元素 [英] Iterate over array twice (cartesian product) but consider only half the elements
问题描述
我试图迭代一个数组两次以获得元素对(e_i,e_j),但我只想要这样的元素,即i< j。
I am trying to iterate over an array twice to have pairs of elements (e_i,e_j) but I only want the elements such that i < j.
基本上,我想要的就像C语言一样。
Basically, what I want would look like this is C-like languages.
int my_array[N] = ...;
for (int i=0; i<N; i++)
for (int j=i+1; j<N; j++)
something(my_array[i],my_array[j]);
我在 itertools (我发现最接近的是 itertools.product(* iterables [,repeat])
)。
I didn't find what I was looking for in itertools (the closest thing I've found was itertools.product(*iterables[, repeat])
).
我尝试过一些事情,但我不相信任何事情:
I tried a few things but I am not really convinced by any of them :
my_list=range(10)
# Using enumerate and slices - explicit loop
res=[]
for i,j in enumerate(my_list):
for k in my_list[i+1:]:
res.append((j,k))
print res
# Using enumerate and slices - list comprehension
res=[(j,k) for i,j in enumerate(my_list) for k in my_list[i+1:]]
print res
# Using enumerate and xrange - explicit loop
res=[]
for i,j in enumerate(my_list):
for k in range(i+1, len(my_list)):
res.append((j,my_list[k]))
print res
# Using enumerate and xrange - list comprehension
res=[(j,my_list[k]) for i,j in enumerate(my_list) for k in range(i+1, len(my_list))]
print res
我仍然相信有更好更多的pythonic解决方案。任何建议都是受欢迎的。
I'm still convinced that there is a better and more pythonic solution. Any suggestion is welcome.
推荐答案
只需使用 itertools.combinations(my_list,2)
。
这篇关于迭代数组两次(笛卡尔积)但只考虑一半的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!