Python: combining word lists

I have lists inside the dictionary:

Number_of_lists=3           #user sets this value, can be any positive integer
My_list={}
for j in range(1,Number_of_lists+1):
  My_list[j]=[(x,y,z)]  

Number_of_listsis a user-defined variable. Without knowing in advance the value set by the user, I would finally like to have a combined list of all dictionary lists. For example, if Number_of_lists=3the corresponding lists My_list[1]=[(1,2,3)], My_list[2]=[(4,5,6)], My_list[3]=[(7,8,9)]the result will be as follows:

All_my_lists=My_list[1]+My_list[2]+My_list[3]

where: All_my_lists=[(1,2,3),(4,5,6),(7,8,9)].

So what I'm trying to do is automate the above procedure for all possible:

Number_of_lists=n #where n can be any positive integer

I have lost a little so far trying to use an iterator to add lists and always fail. I am a beginner python, and this is my hobby, so if you answer, please explain everything in your answer, I do this to find out, I do not ask you to do my homework :)

EDIT

@codebox (. ) , My_List, , , . , - .

+5
4

:

>>> Number_of_lists=3 
>>> My_list={}
>>> for j in range(1,Number_of_lists+1):
      My_list[j]=(j,j,j)
>>> All_my_lists=[My_list[x] for x in My_list]

>>> print(All_my_lists)
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

All_my_lists=[My_list[x] for x in My_list] :

All_my_lists=[]
for key in My_list:
   All_my_lists.append(My_list[key])
+1

My_list ( , !), :

Number_of_lists=3
result = []
for j in range(1,Number_of_lists+1):
    result += (x,y,z)
+1

All_my_lists, My_list.

All_my_lists

range(), All_my_lists:

>>> num = 3  # for brevity, I changed Number_of_lists to num
>>> All_my_lists = [tuple(range(num*i + 1, num*(i+1) + 1)) for i in range(0, num)]
>>> All_my_lists
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

grouper() itertools recipe, :

>>> All_my_lists = list(grouper(num, range(1, num*3+1)))
>>> All_my_lists
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

My_lists

Then we can use the dictconstructor along with the list and enumerate()to build the output My_listfrom All_my_list:

>>> My_lists = dict((i+1, [v]) for i,v in enumerate(All_my_lists))
>>> My_lists
{1: [(1, 2, 3)], 2: [(4, 5, 6)], 3: [(7, 8, 9)]}
>>> My_lists[1]
[(1, 2, 3)]
>>> My_lists[2]
[(4, 5, 6)]
>>> My_lists[3]
[(7, 8, 9)]
+1
source

You can try a more functional approach by turning the Number_of_listskey sequence with rangeand selecting from the dictionary map:

My_list={1:[1,2,3], 2:[4,5,6], 3:[7,8,9], 4:[10,11,12]}
Number_of_lists=3
All_my_lists=map(lambda x: tuple(My_list[x]), range(1, Number_of_lists+1))

Output Example:

>>> All_my_lists
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
+1
source

All Articles