gpt4 book ai didi

python - 使用命名元组格式化字符串

转载 作者:行者123 更新时间:2023-12-04 13:36:33 25 4
gpt4 key购买 nike

我想知道是否有一种方法可以使用命名元组的变量列表来有效地格式化字符串,如下所示:

TestResult = collections.namedtuple('TestResults', 'creation_time filter_time total_time')

test = TestResult(1, 2, 3)
string_to_format = '{creation_time}, {filter_time}, {total_time}'.format(test)

而不是只写:
string_to_format = '{}, {}, {}'.format(test.creation_time, test.filter_time, test.total_time)

如果有办法做到这一点,它会被认为是pythonic吗?

谢谢您的回答

最佳答案

你可以做:

>>> string_to_format = '{0.creation_time}, {0.filter_time}, {0.total_time}'.format(test)
>>> string_to_format
'1, 2, 3'

这是 Pythonic 吗?我不知道,但它做了两件被认为是 Pythonic 的事情: 1. 不要重复自己! ( test 只出现一次)和 2. 明确! (namedtuple 中的名称可以使用)

关于python - 使用命名元组格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50655608/

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