I have a list:
[[[1, 2, 3]], [1, 2, 3], [[2]]]
Is there a way to add a random value to all the items without having to do something like this:
from random import randit [[[list[0][0][0]+randit(0, 10), list[0][0][1]+randit(0, 10), list[0][0][2]+randit(0, 10)]],..
Advertisement
Answer
One option is to use a recursion:
from random import randint def substitute(lst): if isinstance(lst, int): return lst + randint(1, 10) else: for i, item in enumerate(lst): lst[i] = substitute(item) return lst your_list = [[[1, 2, 3]], [1, 2, 3], [[2]]] print(your_list) print(substitute(your_list))
outputs:
>>>[[[1, 2, 3]], [1, 2, 3], [[2]]] >>>[[[10, 10, 5]], [11, 9, 7], [[6]]]
Can also phrased in one line:
from random import randint def recursion(lst): return lst + randint(1, 10) if isinstance(lst, int) else [recursion(item) for item in lst]