ich hab da ein kleines Problem:
Ich möchte variablennamen zusammensetzen, ungefähr so hatte ich mir das vorgestellt:
Code: Alles auswählen
zufall=randint(1,9)
variable+str(zufall)='hallo'
Weiß jemand eine andere variante (möglichst einfach)?
Code: Alles auswählen
zufall=randint(1,9)
variable+str(zufall)='hallo'
Code: Alles auswählen
In [1]: from random import randint
In [2]: zufall = randint(1, 9)
In [3]: variable = 'hallo %d' % zufall
In [4]: print variable
hallo 5
Code: Alles auswählen
In [1]: from random import randint
In [2]: dictionary = {}
In [3]: zufall = randint(1, 9)
In [4]: dictionary['variable%d' %zufall] = 'hallo'
In [5]: dictionary
Out[5]: {'variable6': 'hallo'}
Code: Alles auswählen
In [1]: from random import randint
In [2]: dictionary = {}
In [4]: dictionary['variable%d' % randint(1, 9)] = 'hallo'
In [5]: dictionary['variable%d' % randint(1, 9)] = 'hallo nummer 2'
In [6]: print dictionary
{'variable2': 'hallo nummer 2', 'variable6': 'hallo'}
In [7]: print dictionary['variable2']
hallo nummer 2
Code: Alles auswählen
In [5]: variable = dict()
In [6]: variable[random.randint(0, 9)] = 'hallo'
In [7]: variable
Out[7]: {3: 'hallo'}
In [8]: variable[3]
Out[8]: 'hallo'
Code: Alles auswählen
if zufall==1:
variable1='belegt'
elif zufall==2:
variable2='belegt'
...
Code: Alles auswählen
def set(var, x, y, value):
var[(x,y)] = value
def is_set(var, x, y, value):
return (x,y) in var.keys() and var[(x,y)] == value
variable = {}
set(variable, 1, 1, "spam")
is_set(variable, 1, 1, "spam") # => True
is_set(variable, 2, 3, "eggs") # => False
Code: Alles auswählen
>>> from random import randint
>>> string = "variable%d = 'hallo'"%randint(1,9)
>>> exec(string)
#
# So jetzt müssen wir aber die Vairable suchen und deshalb ist ein dict besser:
#
>>> variable1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'variable1' is not defined
>>> variable2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'variable2' is not defined
>>> variable2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'variable2' is not defined
>>> variable3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'variable3' is not defined
>>> variable4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'variable4' is not defined
>>> variable5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'variable5' is not defined
>>> variable6
'hallo'
>>>
Code: Alles auswählen
from random import randint
myNamespace = dict()
eval("var%d=False" %randint(1,9)) in myNamespace
Och mennobirkenfeld hat geschrieben:Reingefallen: `in` gibts nur bei `exec`. Für `eval` sind die Namespaces ganz normale Argumente