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

前端 未结 3 1304
感动是毒
感动是毒 2021-01-14 05:18

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 lik

相关标签:
3条回答
  • 2021-01-14 06:00

    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.

    0 讨论(0)
  • 2021-01-14 06:03

    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()
    
    0 讨论(0)
  • 2021-01-14 06:24

    Just use itertools.combinations(my_list, 2).

    0 讨论(0)
提交回复
热议问题