【问题标题】:I do not understand how this Python code works - Unknown programming concept [duplicate]我不明白这个 Python 代码是如何工作的 - 未知的编程概念 [重复]
【发布时间】:2015-12-22 09:17:25
【问题描述】:

对于糟糕的标题,我深表歉意。如果我能够正确地描述我的问题,我会使用 google ;)

我发现了一段python代码能够将ini文件解析成一个名为“store”的python dict:

#!/usr/bin/env python

from ConfigParser import SafeConfigParser

def read(file, store):

    def parse_maybe(section):
        if not confp.has_section(section):
            return False

        if (section == "Main"):
            for left, right in confp.items(section):
                store[left] = right.format(**store)
        return True

    confp = SafeConfigParser()
    confp.read(file)
    parse_maybe("Main")

store = {}
store["basedir"] = "/path/to/somewhere"
read("foo.ini", store)

ini 文件可能包含带有占位符的声明,例如:

[Main]
output = {basedir}/somename.txt

运行代码时,{basedir} 会被 store 中已经定义的“/path/to/somewhere”替换。我猜这个魔力来自这行代码:

store[left] = right.format(**store)

我了解代码的作用。但我不明白如何 这是如何工作的。这个 ** 运算符对字典做了什么?非常感谢您提供指向教程等的指针。

【问题讨论】:

  • 如果这不能解决您的查询,那么谷歌搜索“python 双星”会返回许多其他资源
  • **store 解压字典。如果函数接受关键字参数,并且关键字-值对在字典中,则可以使用 ** 将这些对传递给函数参数
  • @texasflood:这就是答案。谢谢。

标签: python dictionary configparser


【解决方案1】:

我的问题有两个答案:

1) 我不知道格式是否可行:

print "{a} is {b}".format(a="Python", b="great")

Python 很棒

2) ** 操作符本质上是解压字典:

dict = {"a": "Python", "b": "great"}
print "{a} is {b}".format(**dict)

Python 很棒

【讨论】:

    猜你喜欢
    • 2012-07-09
    • 2021-11-03
    • 1970-01-01
    • 2015-10-19
    • 2015-05-19
    • 2014-12-01
    • 2022-01-13
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多