Iterate over array twice (cartesian product) but consider only half the elements

半城伤御伤魂 提交于 2019-12-01 07:55:15

问题


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.

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]);

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

I'm still convinced that there is a better and more pythonic solution. Any suggestion is welcome.


回答1:


Just use itertools.combinations(my_list, 2).




回答2:


Can't you just use the range function and go with:

vect = [...]
for i in range(0, len(vect)):
    for j in range(i+1, len(vect)):
        do_something()



回答3:


I would suggest the following:

midIdx = len(mylist) / 2
[ dosomehing(ele_i, ele_j) for ele_i, ele_j in 
    zip( mylist[0:midIdx], mylist[midIdx + 1:len(mylist)] ) ]

For most interpreted language, for loop is not the best choice. Python provides list comprehension, which is more readable and efficient.



来源:https://stackoverflow.com/questions/17768355/iterate-over-array-twice-cartesian-product-but-consider-only-half-the-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!