2

I am having an issue with producing the correct syntax to place random strings from a list of min into fields with the field calculator.

I have tried the following code:

import random

ran = ['kid', 'many', 'love', 'play']

random.shuffle(ran)

for i in ran:

print i

I am only getting one value? I would like to have a random values throughout the entire field.

3
  • Although you mention the Field Calculator you have not shown how that is needed to demonstrate what you are asking about. Consequently, this looks like a pure Python question that would be better researched or asked (without reference to the Field Calculator) at Stack Overflow.
    – PolyGeo
    Commented Apr 4, 2017 at 19:27
  • My apologies, I would like to place the strings kid, many, love, play into the fields randomly from the first Field down to the last field. Commented Apr 6, 2017 at 15:08
  • how do you do this in a dictionary
    – Akhil
    Commented Oct 16, 2019 at 13:02

2 Answers 2

0

You are looping through everything in your list and only outputting the last value after the shuffle. What you need to do is shuffle it for every field, and return a single record from the list for each row.

Try the following - in the field calculator select Python Parser, click on Show Codeblock, and enter this in the Pre-logic Script Code box:

import random
def list_random(ran):
    random.shuffle(ran)
    return ran[0]

And in the expression, call the function and pass your list:

list_random(['kid', 'many', 'love', 'play'])

This will random shuffle the list for each row, and pass the first value in the shuffled list each time.

enter image description here

enter image description here


Alternatively, instead of shuffling your list, you could select a random list index position for each row:

Pre-logic:

import random
def list_random(ran):
    return ran[random.randint(0,len(ran)-1)]

Expression:

list_random(['kid', 'many', 'love', 'play'])

enter image description here

enter image description here

1
  • Thank you so much, this is exactly what I was trying to accomplish Commented Apr 10, 2017 at 12:30
-1

What do you mean by saying getting one value? When I tested your script, it print shuffled elements from the list. like

import random

ran = ['kid', 'many', 'love', 'play']    
random.shuffle(ran)    
for i in ran:    
  print i

love
many
play
kid
1
  • My apologies, I would like to place the strings kid, many, love, play into the fields randomly from the first Field down to the last field. Commented Apr 6, 2017 at 15:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.