Jump to content

Python get random object and only use it once

Joveice

Hello,

 

I would like to get a random object from json (importing json I have done myself) but I can only use 1 object once, so if I have a list of 200 objects, and I do a for N times it will select random objects each time, but it will not select the same over again until it's run again.

 

How can I do this?

I do not have a code sample.

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

7 minutes ago, Dat Guy said:

What have you tried to solve the problem?

to add them all to a list after so I can check if it was used, but it didn't work out well.

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

9 hours ago, Joveice said:

to add them all to a list after so I can check if it was used, but it didn't work out well.

I'm not sure what your fascination with randomizing things is at the moment, but this is actually quite simple. Put a reference to each object in a list. Randomly index the list. remove that reference from the list and call the object it references. rinse and repeat.

If you'll be doing this repeatedly there are some other, faster algorithms to use that don't require repeatedly building the list.

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

Can you not load json objects from a file into a json variable type in python.. maybe you should just look for a 3rd party json handler. I kinda sounds like you are trying to use the data from an io function, either way you need to unload the data into a safer place. if your objects aren't complete monsters I guess you could use multidimensional arrays to hack a handler.

If your using the objects for anything else than get and print you will need to store the data first pull anyway else you will be pushing and throwing data everywhere. else use his idea :):) ^^

Link to comment
Share on other sites

Link to post
Share on other sites

8 hours ago, Ailithic said:

Can you not load json objects from a file into a json variable type in python.. maybe you should just look for a 3rd party json handler.

Import json 

J = json.loads()

 

Just add all the objects to a list then shuffle them and loop the list. 

 

from random import sample
import json
myJson = json.loads('[{"name":"name1"},{"name": "bob"},{"name": "amy"},{"name": "geoff"},{"name": "dan"}]')
  

for item in sample(myJson, len(myJson)):
  print(item)

 

output is different each time, 

 

{'name': 'amy'}
{'name': 'bob'}
{'name': 'geoff'}
{'name': 'name1'}
{'name': 'dan'}

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

If you want to randomly select an item from the list and never select that item randomly again you can use:

import random
AList=[1,2,3,4,5]

def GetItem(List):  # pass the list you want to get the random item from
  index =random.randint(0,len(List)-1)  #creates in index of a random item in the list
  return List.pop(index) # removes the item from the list and returns it.

 

Link to comment
Share on other sites

Link to post
Share on other sites

11 hours ago, ScratchCat said:

If you want to randomly select an item from the list and never select that item randomly again you can use:

This is what I suggested, just with code:

 

On 1/10/2018 at 3:40 PM, straight_stewie said:

Put a reference to each object in a list. Randomly index the list. remove that reference from the list and call the object it references. rinse and repeat.

 

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, straight_stewie said:

This is what I suggested, just with code:

 

 

Apologies, I did not read all the messages , the general gist of the others seemed to be centred around dealing with the json file.

Link to comment
Share on other sites

Link to post
Share on other sites

10 hours ago, ScratchCat said:

Apologies, I did not read all the messages , the general gist of the others seemed to be centred around dealing with the json file.

I kind of came off like a butthole there. I didn't mean to do that, I'm sorry.

I see that, though I have to assume that if someone is working with a file that stores information for them, then they already know how to get the data in and out of the file.

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

On 17/01/2018 at 6:25 PM, ScratchCat said:

If you want to randomly select an item from the list and never select that item randomly again you can use:


import random
AList=[1,2,3,4,5]

def GetItem(List):  # pass the list you want to get the random item from
  index =random.randint(0,len(List)-1)  #creates in index of a random item in the list
  return List.pop(index) # removes the item from the list and returns it.

 

Why would you pass it a list to pop one when you can use pop just in a for loop. Seems like an unnecessary step to me

 

Also just looping the list to the end would only use each item once without the need to manipulate the list. 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

16 hours ago, vorticalbox said:

Also just looping the list to the end would only use each item once without the need to manipulate the list. 

We don't really know enough about what the OP means by "randomly select a method from a list" to know what the best solution is. Is the list built randomly, or is the list ordered and needs to be accessed randomly?

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

The list is not ordered and I just need a random object from it each time I call it, if I call it more than once I can not have the same element selected etc a file of 20 can max be used 20 times at once.

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

9 hours ago, Joveice said:

The list is not ordered and I just need a random object from it each time I call it, if I call it more than once I can not have the same element selected etc a file of 20 can max be used 20 times at once.

If there is only one of each item in a file no duplicates then shuffle the list and just loop to the end. 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Make an array of 200 values.

Put a random number between 1 and 200 in the first position.

Go from 2nd position to the last ,  for each of these positions :

    pick a random number between 1 to 200

    is this number already stored in positions 1 to current position -1

      if yes, then go back and pick another number

      if no, store the number at this position and you're done, advance to next position

Now you have 200 random non repeating numbers in your array of 200 values.

 

php has more elegant ways to do it, has built in functions to randomize arrays, shuffle things, but the code below would be easy to adapt to python i guess

 

php code :

 

$numbers = array();

$numbers[0] = mt_rand(1,200);

$value = 0;

for ($i=1;$i<200;$i++) {
	$can_use = FALSE;
	while ($can_use == FALSE) {
		$value = mt_rand(1,200); // potential value
		$can_use = TRUE; 		 // assume we can use               
		for ($j=0;$j<$i;$j++) {
			if ($numbers[$j] == $value) {
				$can_use=FALSE;  // number found in prev. positions in array
			}
		}
	}
	$numbers[$i] = $value;
}
 

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

16 minutes ago, mariushm said:

Make an array of 200 values.

Put a random number between 1 and 200 in the first position.

Go from 2nd position to the last ,  for each of these positions :

    pick a random number between 1 to 200

    is this number already stored in positions 1 to current position -1

      if yes, then go back and pick another number

      if no, store the number at this position and you're done, advance to next position

Now you have 200 random non repeating numbers in your array of 200 values.

 

php has more elegant ways to do it, has built in functions to randomize arrays, shuffle things, but the code below would be easy to adapt to python i guess

 

php code :

 

 

 

Sounds like over complicating things.

 

I really like the ideas @vorticalbox, @straight_stewie, @ScratchCat came up with.

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

On 1/19/2018 at 7:11 AM, vorticalbox said:

Why would you pass it a list to pop one when you can use pop just in a for loop. Seems like an unnecessary step to me

 

Also just looping the list to the end would only use each item once without the need to manipulate the list. 

It was just to create a demonstration function. It is unnecessary but just may be convenient if the OP wants to alter the program e.g. Get a random item from the second half of the list.

The OP wanted items in a random order from the list, therefore using the original list would not fully work. I guess iterating through a shuffled version using :

import random
l =[1,2,3,4,5]
random.shuffle(l)
#l now contains a randomly shuffled list

Use whatever library can shuffle a list for you.

Link to comment
Share on other sites

Link to post
Share on other sites

Well currently I did this

locations = json.load(open('locations.json'))
locationsCount = len(locations) - 1
tempLoc = locations[random.randint(0, locationsCount)]

Works great, but I did not see how I where to only select a element once and never again in the same run.

 

But to remove the element from the list and update the count would probably work?

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

34 minutes ago, Joveice said:

Sounds like over complicating things.

 

It depends on the size of those json objects.  Shuffling lists and push-ing and pop-ing objects in arrays can cause a bunch of memory to be moved around, to have memory allocated and deallocated... that can take cpu cycles... you may not want to do that for example each time you're rendering a frame in a video game.

In my example, we're talking about only around 1 KB of memory (200 x 32bits per number plus some extra data for the array definition) and the time it takes to pick 200 random numbers is predictable and finite (you can estimate the worst case scenario)

 

Link to comment
Share on other sites

Link to post
Share on other sites

27 minutes ago, Erik Sieghart said:

Here you go.
 

rand_ob.zip

I don't download files from unknown sources sorry.

 

But I think I have got a good idea of a way to do this now.

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×