0

I have a list of NamedTuples (short extract below) and wrote some code to add the same random value to each of the a and b values in the tuple. The list will vary in length.

This works ok but I now need to add a different random value to each of the a and b values.

So, as written randomise will generate a random value between -5 and 5 and apply that value to all instances of a and b. Now I want to add a different value to each instance of a and b.

What is the quickest way (in terms of execution) of doing this?

Extract:

list_one = [Test(a=820, b=625, time=1643282249.9990437), Test(a=820, b=624, time=1643282250.0470896), Test(a=820, b=623, time=1643282250.1034527), Pass(test_type='do1', pass='ffg3', time=1643282250.7834597)]

Code:

randomise = random.randint(-5, 5)
list_one = [Test(t.a + randomise, t.b + randomise, t.time) if isinstance(t, Test) else t for t in list_one]
S.B
  • 13,077
  • 10
  • 22
  • 49
Robsmith
  • 339
  • 1
  • 8
  • Do you mean one value for `a` and one value for `b`, same for all tuples. Or same value for `a` and `b` but different between each tuple? – Tomerikoo Jan 27 '22 at 11:34
  • Hi @Tomerikoo a random value generated for each a and b. So, a random value generated for every instance. Eg say there were 10 as and 10 bs in the list. I need 20 random values between -5 and 5. – Robsmith Jan 27 '22 at 11:40
  • 1
    Then just don't randomize one number in the start... Why not just `[Test(t.a + randint(-5, 5), t.b + randint(-5, 5), ...]` – Tomerikoo Jan 27 '22 at 12:17

1 Answers1

1

You can just create a lambda which will probably create a different offset each time it is called:

randomise = lambda: random.randint(-5, 5)
list_one = [Test(t.a + randomise(), t.b + randomise(), t.time) if isinstance(t, Test) else t for t in list_one]
quamrana
  • 37,849
  • 12
  • 53
  • 71