V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
diwuqin
V2EX  ›  Python

如何使用便利字典后的 index 做为列表名称创建列表呢

  •  
  •   diwuqin · 2021-01-07 11:45:29 +08:00 · 1880 次点击
    这是一个创建于 1204 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如题, 我又一个字典 a 遍历之后获取到的键名称'test', 用这个 test 创建一个名为 test 的空列表
    10 条回复    2021-01-12 13:44:20 +08:00
    xiaochun41
        1
    xiaochun41  
       2021-01-07 12:35:39 +08:00
    exec,eval 可以了解下。
    todd7zhang
        2
    todd7zhang  
       2021-01-07 16:00:08 +08:00
    k = 'test'
    globals()[k] = []

    test.append(3)

    不建议这么玩,哈哈
    krixaar
        3
    krixaar  
       2021-01-07 16:09:05 +08:00
    接#2,直接玩 globals()还是有点危险,所以可以自己搞一个汇总字典,例如:
    k = 'test'
    glöbals = {}
    glöbals[k] = []

    glöbals['test'].append(3)

    print(glöbals['test'])

    🤣
    Yvvon
        4
    Yvvon  
       2021-01-07 16:31:25 +08:00
    a = {'test1': 1, 'test2': 2}

    for k, v in a.items():
    print(k)
    exec(f'{k} = []')
    print(test1)
    print(test2)
    jmc891205
        5
    jmc891205  
       2021-01-07 16:38:31 +08:00
    你还是讲讲为什么你有这种需求吧

    XY problem 了解一下: https://en.wikipedia.org/wiki/XY_problem
    Vegetable
        6
    Vegetable  
       2021-01-07 17:00:34 +08:00   ❤️ 1
    这个需求非常奇怪,一定是哪里有问题。
    如果一定要用,就只能
    locals().setdefault('test',list())

    setdefault 避免覆盖现有变量,但是需要更多的工作判断是否创建成功,进一步来说,你编码时不知道变量名,想使用这个变量又只能使用 locals()或者 globals(),无法通过字面调用。那创建这个变量的意义又在哪呢
    HelloViper
        7
    HelloViper  
       2021-01-08 10:44:40 +08:00
    这种需求一般是要批量创建对象

    你直接用字典管理,访问对象用 key 来索引:
    {"test1":obj(*params1),"test2":obj(*params2)....}
    diwuqin
        8
    diwuqin  
    OP
       2021-01-11 11:44:30 +08:00
    @jmc891205 #5 遍历的字典要创建对应的列表数据
    diwuqin
        9
    diwuqin  
    OP
       2021-01-11 11:45:08 +08:00
    已解决, 多谢各位~
    canwushuang
        10
    canwushuang  
       2021-01-12 13:44:20 +08:00
    程序中名字不重要,一切都是指针。典型的 xy 问题
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1811 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 16:35 · PVG 00:35 · LAX 09:35 · JFK 12:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.