如何动态创建变量? [英] How can you dynamically create variables?

查看:29
本文介绍了如何动态创建变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Python 中动态创建变量.有没有人有任何创造性的方法来做到这一点?

I want to create variables dynamically in Python. Does anyone have any creative means of doing this?

推荐答案

除非非常需要创建一堆乱七八糟的变量名,否则我只会使用字典,您可以在其中动态创建键名并关联一个值给每个人.

Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.

a = {}
k = 0
while k < 10:
    # dynamically create key
    key = ...
    # calculate value
    value = ...
    a[key] = value 
    k += 1

新的collections模块中还有一些有趣的数据结构 可能适用.

There are also some interesting data structures in the new collections module that might be applicable.

这篇关于如何动态创建变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆