import random
alphabet = tuple('abcdefghijklmnopqrstuvwxyz')
print '\n'.join(repr(u) for u in globals() if not u.startswith('__'))
for i in xrange(8):
globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)
print
print '\n'.join(repr((u,globals()[u])) for u in globals() if not u.startswith('__'))
使用globals()可以:
一个结果:
我使用random是因为你没有解释要给出哪些“变量”的名称,以及要创建哪些值。因为我认为不将名称绑定到对象就不可能创建名称。
使用exec()方法。例如,假设您有一个字典,并且希望将每个键转换为一个具有其原始字典值的变量,可以执行以下操作。
Python 2
Python 3
除非迫切需要创建一堆变量名,否则我只需要使用字典,在字典中,您可以动态创建键名并将每个键名关联一个值。
新的“collections”模块中还有一些有趣的数据结构可能适用:
http://docs.python.org/dev/library/collections.html
相关问题 更多 >
编程相关推荐