How to compare each item in a list with the rest, only once?

后端 未结 5 519
误落风尘
误落风尘 2020-12-07 09:02

Say I have an array/list of things I want to compare. In languages I am more familiar with, I would do something like

for (int i = 0, i < mylist.size(); i         


        
5条回答
  •  心在旅途
    2020-12-07 09:22

    Of course this will generate each pair twice as each for loop will go through every item of the list.

    You could use some itertools magic here to generate all possible combinations:

    import itertools
    for a, b in itertools.combinations(mylist, 2):
        compare(a, b)
    

    itertools.combinations will pair each element with each other element in the iterable, but only once.


    You could still write this using index-based item access, equivalent to what you are used to, using nested for loops:

    for i in range(len(mylist)):
        for j in range(i + 1, len(mylist)):
            compare(mylist[i], mylist[j])
    

    Of course this may not look as nice and pythonic but sometimes this is still the easiest and most comprehensible solution, so you should not shy away from solving problems like that.

提交回复
热议问题