I'd like to ask you a question about automatic Python variable generation

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

a1 = 0 
a2 = 0
.
.
a (to the desired number) = 0

I want to make as many variables as I want and put a value of 0 in the for or while statement How do I automatically generate variables?

Do you have any chance to automatically create dictionaries?

 a1 = { food value: 10, speed: 10}
.
.
a (to the desired number) = a1 = {Food value: 10, speed: 10}

Is that possible?

python

2022-09-20 10:58

1 Answers

a = [ 0 for _ in range(N) ]

print(a[0])

print(a[N-1])
>> a = [{"food value":10, "speed":10} for _in range(N)]
>>> a
[{'Food value': 10, 'Speed': 10}, {'Food value': 10, 'Speed': 10}, {'Food value': 10, 'Speed': 10}, {'Food value': 10, 'Food value': 10}, {'Food value': 10}, {'Food value: 10}
>>> a[0]
{'Food value': 10, 'speed': 10}
>>> a[0]["Food Value"] += 1
>>> a[0]
{'Food value': 11, 'speed': 10}
>>> a[1]
{'Food value': 10, 'speed': 10}
>>> a[2]
{'Food value': 10, 'speed': 10}

a{number} It is not good to dynamically generate variables of the same type. It's cumbersome to make, and it's cumbersome to rewrite.

It's much more natural and simple to just use a basic list or dictionary.

>>> import random
>>> random.randint(1, 10)
4
>>> a = [{ "food value":random.randint(1, 10), "speed":random.randint(1, 10),
    "x":random.randint(5, 10), "y":random.randint(-5, 3)} for _ in range(10) ]
>>> import pprint
>>> pprint.pprint(a)
[{'x': 9, 'y': 1, 'speed': 1, 'food value': 4},
 {'x': 8, 'y': 2, 'speed': 5, 'food value': 1},
 {'x': 7, 'y': -1, 'speed': 3, 'food value': 10},
 {'x': 9, 'y': 2, 'speed': 7, 'food value': 5},
 {'x': 9, 'y': 3, 'speed': 2, 'food value': 4},
 {'x': 7, 'y': -4, 'speed': 5, 'food value': 6},
 {'x': 5, 'y': -2, 'speed': 7, 'food value': 3},
 {'x': 5, 'y': 1, 'speed': 6, 'food value': 1},
 {'x': 6, 'y': 2, 'speed': 8, 'food value': 9},
 {'x': 8, 'y': 2, 'speed': 5, 'food value': 10}]
>>> a[0]
{'Food value': 4, 'speed': 1, 'x': 9, 'y': 1)
>>> a[1]
{'Food value': 1, 'speed': 5, 'x': 8, 'y': 2'
>>> a[9]
{'Food value': 10, 'speed': 5, 'x': 8, 'y': 2'


2022-09-20 10:58

If you have any answers or tips


© 2022 pinfo. All rights reserved.