V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
frmongo
V2EX  ›  Python

设置多个 global 变量有没有方便的操作?

  •  
  •   frmongo · Oct 19, 2020 · 2537 views
    This topic created in 2017 days ago, the information mentioned may be changed or developed.

    语言 python3, 比如我要设置 50 个变量为全局变量,都是类似这句话

    global para_1 
    

    除了写 50 行声明语句,有用几行就能实现的写法吗?

    11 replies    2020-10-19 17:41:40 +08:00
    frmongo
        1
    frmongo  
    OP
       Oct 19, 2020
    我找到一种稍微简便的写法

    global para_1,para_2...para_50

    还有别的方法吗
    kiracyan
        2
    kiracyan  
       Oct 19, 2020
    用脚本写
    BingoXuan
        3
    BingoXuan  
       Oct 19, 2020 via Android
    注入 globals 的字典
    frmongo
        4
    frmongo  
    OP
       Oct 19, 2020
    @BingoXuan cool
    zxCoder
        5
    zxCoder  
       Oct 19, 2020
    数组
    laike9m
        6
    laike9m  
       Oct 19, 2020   ❤️ 1
    > 我要设置 50 个变量为全局变量

    那你可能需要重构一下代码了
    JB18CM
        7
    JB18CM  
       Oct 19, 2020
    切片
    yucongo
        8
    yucongo  
       Oct 19, 2020
    p_list = [f'para_{idx}' for idx in range(1, 51)]
    globals().update(dict(zip(p_list, [None] * 50)))
    typetraits
        9
    typetraits  
       Oct 19, 2020   ❤️ 1
    50 个?不如直接存入一个 dict,然后把这个 dict 放到 globals 里
    faketemp
        10
    faketemp  
       Oct 19, 2020
    只有我一个人把标题看成"golang 变量"了吗
    frmongo
        11
    frmongo  
    OP
       Oct 19, 2020
    @typetraits 嗯,多谢,我现在就这些写的
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4047 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 10:21 · PVG 18:21 · LAX 03:21 · JFK 06:21
    ♥ Do have faith in what you're doing.