Reputation:
I am making a game which requires me to randomly select 2 buildings from a pool of different buildings, and after choosing 1 of the 2 buildings the count from the building pool will be deducted. I am having troubles changing the values of the selected items in the nested loop. Is there any way I can change it? This is my current code:
building_list = [['house', 8], ['hospital', 8], ['shopping-center', 8], ['airport', 8], ['park', 8]]
building_list1 = random.choice(building_list)[0]
building_list2 = random.choice(building_list)[0]
Upvotes: 2
Views: 99
Reputation: 4980
If you have concern about the performance of removing the "chosen" building, then I will propose different approach to this problem. The reason is that to constant search and remove list item is not efficient.
Please let me know if you have question.
n = 2 # select 2 buildings to pop
while n: # n is not zero: means it's True
random.shuffle(building_list)
building_pop = building_list.pop() # remove last item from list is O(1)
print(build_pop)
# do whatever you want to this two building here <----
n -= 1
Upvotes: 1
Reputation: 137
this looks complex but basically we are finding what the random item was then decrementing its value by 1 then getting the name of the building.
import random
building_list = [['house', 8], ['hospital', 8], ['shopping-center', 8],
['airport', 8], ['park', 8]]
building1 = random.choice(building_list)
building_list[building_list.index(building1)][1] -= 1
building_list1 = building1[0]
print(building1)
print(building_list1)
building2 = random.choice(building_list)
building_list[building_list.index(building2)][1] -= 1
building_list2 = building2[0]
print(building2)
print(building_list2)
I got this output:
['shopping-center', 7]
shopping-center
['hospital', 7]
hospital
Upvotes: 1