14

I need to fill a field with false string data from a given list randomly. There are rand and randf functions generating random numbers. There is a similar (not identical) question: Updating attribute field with random string value. But it doesn't meet my need. Also, the answer in that post does not work as expected.

How can I fill the field with a random string from a list, preferably using existing functions?

Pseudo-expression I need: randstr(['A', 'B', 'C']).

3 Answers 3

18

You can build the array, build a random index and extract its value

array('a','b','c')[rand(0,2)]
3
  • 2
    less quotes : string_to_array('A,B,C', ',')[rand(0, 2)] Apr 30, 2021 at 13:31
  • 3
    @J.Monticolo but 41% more characters :-)
    – JGH
    Apr 30, 2021 at 13:35
  • For a short list of strings it is quite short. I didn't imagine using like that. Thanks. Apr 30, 2021 at 13:53
13

I'm not an expression expert. My solution uses a custom function.

Function definition:

from qgis.core import *
from qgis.gui import *
import random

@qgsfunction(args=-1, group='Custom')
def randstr(in_list, feature, parent):
    return random.choice(in_list)

Usage:

randstr('A', 'B', 'C')
10

You can try an expression like this:

with_variable('stringlist',array('string_a','string_b','string_c'),
array_get(@stringlist,rand(0,array_length(@stringlist)-1)))

Explanation: First set up an array as variable, so you only have to build your lookup-array once. Next we pickup a random position from this array using array_get() combined with rand(). The minimum value is 0, as the array is 0 based. Because of that, we also need to remove 1 from array_length(), which is not 0 based, serving as maximum value.

Your Answer

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

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