I would like you to help solve the problem, the essence is:
There is a code whose purpose is to select random values ​​from an array of groups until these values ​​actually run out. The code is:

import vk, csv, random session = vk.Session() api = vk.API(session) with open('current_groups_2.csv', 'r') as f: reader = csv.reader(f) reader = map(int, f) group_list = list(reader) if random.choice(group_list) > 0: x = random.choice(group_list) photo = api.groups.getById(group_id = x, fields = 'members_count') print(sorted(photo)) 

So far, the variable x is assigned one value. How to make the program after each pass choose a new value of x?

Thank you in advance.

3 answers 3

To get all items from the list in random order:

 random.shuffle(group_list) for group_id in group_list: #... 

    if group_list is updated while running:

     while group_list: # случайный индекс group_list i = random.randrange(len(group_list)) # поменять местами случайный индекс и последний элемент group_list[i], group_list[-1] = group_list[-1], group_list[i] x = group_list.pop() # pop последний элемент O(1) 

      If I correctly understood what you need, you first need to shuffle the group_list list, then extract the last element in the loop from it until the list is empty. We obtain a random sequence of all values ​​of the list. The code is:

       import vk, csv, random session = vk.Session() api = vk.API(session) with open('current_groups_2.csv', 'r') as f: reader = csv.reader(f) reader = map(int, f) group_list = list(reader) random.shuffle(group_list) while group_list: x = group_list.pop() photo = api.groups.getById(group_id = x, fields = 'members_count') print(sorted(photo)) 

      Since the list is shuffled randomly, the pop method will return an element with random content each time and remove it from the list. Since an element is removed from the end of the list, when an element is deleted, the index elements of the list elements are not recalculated and the code works efficiently. Further, inside the same code block (inside the loop body) we do something with the received element.