为什么我必须在 str.format(*args, **kwargs) 中的列表前面使用 *

Why do I have to use * in front of a list in str.format(*args, **kwargs)

看完这些:
Special use of args / kwargs
https://www.python.org/dev/peps/pep-3102/
What does ** (double star) and * (star) do for parameters?
https://docs.python.org/3.5/library/string.html#formatstrings

我想确保我理解得很好:str.format(*args, **kwargs)

if uniques 是两个整数的列表,例如 [0, 0],我将在循环中使用它,例如在有条件递增第一个元素而没有条件递增第二个元素的情况下,有:

 print('Task finished. {0!s} retrieved out of {1!s} tested'.format(*uniques))

我必须使用 *uniques 因为 uniques 将作为元组传递给格式。但是如果我确实使用

 print('Task finished. {0.[0]} retrieved out of {0.[1]} tested'.format(uniques))

引发值错误:ValueError: Empty attribute in format string。在 uniques 周围使用方括号没有帮助。我真的不明白为什么?有人可以澄清一下吗?

第一种情况是list解包后转成tuple,第二种情况不是,因为list不能马上按格式转成tuple,同理format(uniques[0], uniques[1]) 会吗?如果我是对的,为什么会这样,因为有一个 tuple(list) 函数可以做到这一点,所以它非常简单?

您的格式字符串中有错字:

print('Task finished. {0[0]} retrieved out of {0[1]} tested'.format(uniques))

您正在混合使用 attributesubscription 语法。 0.[0] 告诉格式查找名称为 [0] 属性 。但是,点后面的 formal grammar only allows for a valid identifier(表示由字母、数字和下划线组成的单词,以字母或下划线开头)和 [0] 不符合该规则,因此会出现错误根本没有属性名称。

落点:

print('Task finished. {0[0]} retrieved out of {0[1]} tested'.format(uniques))

这现在可以工作了,因为现在格式解析器可以正确地看到订阅:

>>> uniques = [0, 0]
>>> print('Task finished. {0[0]} retrieved out of {0[1]} tested'.format(uniques))
Task finished. 0 retrieved out of 0 tested
>>> uniques = [42, 81]
>>> print('Task finished. {0[0]} retrieved out of {0[1]} tested'.format(uniques))
Task finished. 42 retrieved out of 81 tested

0[0] 说明符告诉 str.format 解析器使用第一个位置参数(此处由 uniques 提供),然后通过订阅 [0], 所以第一个元素.

当你使用 '...'.format(*uniques) 时,任何 iterable 都可以,无论是列表、元组还是不同类型的可迭代对象(包括生成器); Python 迭代它以产生单独的参数。对于 [42, 81],这意味着 Python 将调用该方法,就像您使用 '...'.format(42, 81) 调用它一样。在字符串格式中,您必须使用 {0}{1}.

来处理这些单独的参数