2

This itertools example compares only 1 item to another. I need to compare 1 item to 2 others at the same time.

my_list = [10, 420, 11]

I need to be able to compare these items in the query below, with the following comparisons:

  • 10 to both 420 and 11 (as in the code below),
  • 420 to both 10 and 11,
  • 11 to both 420 and 10.

I'm running this inside of a SQL query.

SELECT COUNT(*) FROM (
   SELECT app FROM vendor WHERE vendor=10 AND active
   INTERSECT
   SELECT app FROM vendor WHERE vendor NOT IN (420, 11) AND active = 0
   )
uber
  • 4,163
  • 5
  • 26
  • 55
  • 1
    What do you mean by "compare"? Do you mean `if 10 in [420, 11]`? – Barmar Feb 19 '21 at 18:26
  • I should have said loop over. editing question now – uber Feb 19 '21 at 18:26
  • 1
    It still says "compare". What do you mean by that? – Barmar Feb 19 '21 at 18:28
  • Where in the query is it comparing items in the list to each other? It's comparing vendors in the table to items in the list. – Barmar Feb 19 '21 at 18:30
  • if I do ```for i, k in itertools.combinations``` I only have two items to do whatever operation with them. I need three items. I'm having a hard time explaining - Please look at the query in the question and imagine swapping the 1st vendor number, and then on the second SELECT changing the values inside parentheses for the remaining values of the list. – uber Feb 19 '21 at 18:31
  • It seems like you just want to extract each item from the list, and then get a list of the remaining items. – Barmar Feb 19 '21 at 18:32
  • that's about right! how to do that iteratively? – uber Feb 19 '21 at 18:33

2 Answers2

2

This will compare all possible combinations of elements from your list.

arr = [10, 420, 11]

for i, el in enumerate(arr):
    leftover = arr[:i] + arr[i+1:]
    print(el, leftover, el in leftover)

prints the following:

10 [420, 11] False
420 [10, 11] False
11 [10, 420] False
Yulian
  • 365
  • 4
  • 12
2

Write a function that returns a copy of a list with a specified element removed. Then iterate over the list, returning each item and the list with that item removed.

def list_without(l, i):
    result = l[:] # copy list
    l.pop(i) # remove the specified index
    return l

my_list = [10, 420, 11]

my_combinations = [(item, list_without(my_list, i)) for i, item in enumerate(my_list)]
print(my_combinations)
# output:
# [(10, (420, 11)), (420, (10, 11)), (11, (10, 420))]
Barmar
  • 741,623
  • 53
  • 500
  • 612