1

For example, I have gathered a list of the lowest numbers of a list and I need to divide them by each other but repeat themselves down the list similar to a Cartesian product.

Not exact code below, but similar. Exact code would just be confusing if I posted it.

lowestnumbers = [2,3,4,5,6,7,8]
highestnumbers = [2,3,4,5,6,7,8]
for matchhigh in highestnumbers:
    print (matchhigh)
for matchlow in lowestnumbers:
    print (matchlow)
    percentage = (matchlow / matchhigh - 1.0)
    print (percentage)

When I've done this, it repeats the last number of from "matchhigh" and repeatedly divides itself by that last number.

I need something to do something along the lines of below and I'm completely lost.

list1 = [1,2,3]
list2 = [3,2,1]
for number in list1
     answer = number / list2
     print = answer

Desired Output:

0.3333333333333333
0.5
1
0.6666666666666667
1
2
1
1.5
3

Please let me know if there is a solution to the issue I am having, it's driving me insane.

Mario
  • 13
  • 3

2 Answers2

1

A nested loop will do:

>>> list1 = [1,2,3]
>>> list2 = [3,2,1]
>>> for x1 in list1:
...     for x2 in list2:
...         print(x1/x2)  # Python3
...         print(float(x1)/x2)  # Python2

Or itertools.product:

>>> from itertools import product
>>> for x1, x2 in product(list1, list2):
...     print(x1/x2)  # Python3
...     print(float(x1)/x2)  # Python2

0.3333333333333333
0.5
1.0
0.6666666666666666
1.0
2.0
1.0
1.5
3.0
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Worked great! Thank you, I knew it would be something simple. Now time to find out how to split this list accordingly, should be easy from here on out. :) – Mario Jan 08 '18 at 11:27
0
from itertools import product

div_list = [a / b for a, b in product(list1, list2)]

print('\n'.join(str(x) for x in div_list))
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135