Setting maximum value of Range() in For loop - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Setting maximum value of Range() in For loop (/thread-20308.html) |
Setting maximum value of Range() in For loop - pmt - Aug-04-2019 Hello all, I am trying to use range() and for loop function to change the dictionary keys and values. Expected output result is to create the keys and values of t{} according to the values in f_set. The expected result is e.g I would like to create f_set[0]=(e.g 5) and f_set[1]=e.g 2 values and get the t output as {(1, 2, 1): 1, (1, 2, 2): 1, (1, 2, 3): 1, (1, 2, 4): 1, (1, 2, 5): 1,(1, 3, 1): 1, (1, 3, 2): 1}. However, the current output is always taking the maximum value fro m f_set as final value. How can I get the t output as I want to create? Thanks for any help. N=[1,2,3] t={} f_set=[5,2,1,10,15,1,3,1] for x in N: for y in N: if x is not y: for f in f_set: for f_no in range(1,f+1): t[x,y,f_no]=1 print(t)
RE: Setting maximum value of Range() in For loop - ichabod801 - Aug-04-2019 You are always getting the maximum value for f_set because for each pair of initial values, you are going through every value in f_set (line 7). You only want to get one value in f_set per pair of initial values. N=[1,2,3] t={} f_set=[5,2,1,10,15,1,3,1] f_index = 0 for x in N: for y in N: if x is not y: for f_no in range(1,f_set[f_index]+1): t[x,y,f_no]=1 f_index += 1 print(t) RE: Setting maximum value of Range() in For loop - pmt - Aug-04-2019 Thank you very much for your help. It worked and I could get the result as I want. RE: Setting maximum value of Range() in For loop - DeaD_EyE - Aug-04-2019 With product from itertools you can remove the nested for-loop for x and y .from itertools import product N = [1, 2, 3] t = {} f_set = [5,2,1,10,15,1,3,1] f_index = 0 for x,y in product(N, N): if x is not y: for f_no in range(1, f_set[f_index] + 1): t[x, y, f_no] = 1 f_index += 1 print(t)With a card deck it's easier to understand: from itertools import product from itertools import chain # 2 - 10, Jack, Queen, King, Ace numbers = chain(range(2,11), ['Jack', 'Queen', 'King', 'Ace']) colors = ['♠', '♡', '♣', '♢'] for color, number in product(colors, numbers): print(f'{color} {number}') RE: Setting maximum value of Range() in For loop - pmt - Aug-04-2019 @DeaD_EyE ..Thanks for your suggestion. |