Python 动态生成变量名
2015-08-25 18:29
691 查看
如果你想生成v1,v2...v100这一百个变量,使用其他静态编译语言只能在代码中手动写出这100个变量名,但是在python中可以使用循环方便地动态生成。
python中有一个函数locals(),定义是:
locals(...)
locals() -> dictionary
Update and return a dictionary containing the current scope's local variables.
即返回当前作用域的所有变量
所以可以用这个函数来创建变量
代码:
输出为1 2 3
python中有一个函数locals(),定义是:
locals(...)
locals() -> dictionary
Update and return a dictionary containing the current scope's local variables.
即返回当前作用域的所有变量
所以可以用这个函数来创建变量
代码:
for i in range(4): name='v'+str(i) locals()['v'+str(i)]=i print v1,v2,v3
输出为1 2 3
相关文章推荐
- python BDD 框架之lettuce(支持中文)
- python学习笔记
- python celery(任务调度器)
- python3爬虫 - 利用浏览器cookie登录
- python3爬虫 - 利用浏览器cookie登录
- python学习笔记之爬虫之爬取百度贴吧某一帖子
- 用python上手金融工程
- Python 虚拟环境:Virtualenv
- python报错
- 大数据全栈式开发语言 – Python
- 机器学习算法与Python实践之逻辑回归(Logistic Regression)
- python - encoding
- Python RuntimeError: thread.__init__() not called
- re,re.search,
- 【Python 练习】随机显示不重复的单词
- python的datetime模块实用小记
- python property装饰器
- Python图像处理库:Pillow 初级教程
- python学习--核心编程3习题解答以及知识点记录
- python学习笔记6—文件操作来生成船只侧面图像的描述文件