gpt4 book ai didi

python - 带有项目查找的字符串格式化参数引用

转载 作者:行者123 更新时间:2023-11-28 17:27:35 25 4
gpt4 key购买 nike

是否可以使用格式字符串参数的值作为其他参数的键?

mins = {'a': 2, 'b': 4, 'c': 3}
maxs = {'a': 12, 'b': 7, 'c': 21}

'{0} {1[{0}]} {2[{0}]}'.format('a', mins, maxs)

我期望 a 2 12 但是 KeyError: '{0}' 被抛出,因为文字字符串 {0} 是用于查找而不是 a

查找可以在调用 format 时完成,但我只是想看看是否可以在字符串中引用其他位置参数。

key = 'a'
'{} {} {}'.format(key, mins[key], maxs[key])

最佳答案

不,根据PEP3101 ,您不能嵌套替换字段:

Format specifiers can themselves contain replacement fields. For example, a field whose field width is itself a parameter could be specified via:

"{0:{1}}".format(a, b)

These 'internal' replacement fields can only occur in the format specifier part of the replacement field. Internal replacement fields cannot themselves have format specifiers. This implies also that replacement fields cannot be nested to arbitrary levels.

您必须将该逻辑从格式字符串中移出:

>>> '{0} {1} {2}'.format('a', mins['a'], maxs['a'])
'a 2 12'

然而,在Python3.6 (目前处于 alpha 阶段)有特殊的 format strings这将有助于以这种方式解决它:

>>> key = "a"
>>> mins = {'a': 2, 'b': 4, 'c': 3}
>>> maxs = {'a': 12, 'b': 7, 'c': 21}
>>> f'{key} {mins[key]} {maxs[key]}'
'a 2 12'

关于python - 带有项目查找的字符串格式化参数引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37499702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com