gbo*_*ffi 25 python python-3.5
我的代码
$ python
Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul 2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = (1, 2)
>>> '%d %d %d' % (0, *a)
'0 1 2'
>>> '%d %d %d' % (*a, 3)
'1 2 3'
>>> '%d %d' % (*a)
File "<stdin>", line 1
SyntaxError: can't use starred expression here
>>>
Run Code Online (Sandbox Code Playgroud)
我的问题,为什么?
用更严肃的语气:我想要一个答案或参考,详细说明使用星号表达的所有细节,因为碰巧我有时会对其行为感到惊讶......
为了反映我的问题后面的一些启发性评论,我添加了以下代码
>>> '%d %d' % (, *a)
File "<stdin>", line 1
'%d %d' % (, *a)
^
SyntaxError: invalid syntax
>>> '%d %d' % (*a,)
'1 2'
>>>
Run Code Online (Sandbox Code Playgroud)
(我(, a)
在发布原始问题之前尝试了这个部分,但我省略了它,因为错误与主演无关.)
有一种语法,在python≥3.5,"只是工作",但我想要一些理解.
Bła*_*lik 30
这是因为:
(a)
Run Code Online (Sandbox Code Playgroud)
只是括号括起来的值.它不是一个新的元组对象.所以你的表达:
>>> '%d %d' % (*a)
Run Code Online (Sandbox Code Playgroud)
将被翻译为:
>>> '%d %d' % * a
Run Code Online (Sandbox Code Playgroud)
这在python语法方面显然是错误的.
为了创建一个新的元组,使用一个表达式作为初始化器,你需要,
在它之后添加一个' ':
>>> '%d %d' % (*a,)
Run Code Online (Sandbox Code Playgroud)
注意:除非a
是生成器,否则在这种特殊情况下你可以输入:
>>> '%d %d' % a
Run Code Online (Sandbox Code Playgroud)
另外,如果我可以提出一些建议:你可以开始使用新式的格式化表达式.他们都是伟大的!
>>> "{} {}".format(*a)
Run Code Online (Sandbox Code Playgroud)
你可以阅读这些详细了解他们牛逼 w ^ ō Python文档中的段落,也有这个伟大的网站.上面的行使用下面描述的参数解包机制.
除了创建新的列表/元组/字典之外,还有更多用于加星标表达的用法.其中大多数都在本PEP中描述,而这一个
所有这些都归结为两种:
RValue拆包:
>>> a, *b, c = range(5)
# a = 0
# b = [1, 2, 3]
# c = 4
>>> 10, *range(2)
(10, 0, 1)
Run Code Online (Sandbox Code Playgroud)
Iterable/dictionary对象初始化(注意你也可以在列表中解压缩字典!):
>>> [1, 2, *[3, 4], *[5], *(6, 7)]
[1, 2, 3, 4, 5, 6, 7]
>>> (1, *[2, 3], *{"a": 1})
(1, 2, 3, 'a')
>>> {"a": 1, **{"b": 2, "c": 3}, **{"c": "new 3", "d": 4}}
{'a': 1, 'b': 2, 'c': 'new 3', 'd': 4}
Run Code Online (Sandbox Code Playgroud)
当然,最常见的用途是参数解包:
positional_arguments = [12, "a string", (1, 2, 3), other_object]
keyword_arguments = {"hostname": "localhost", "port": 8080}
send(*positional_arguments, **keyword_arguments)
Run Code Online (Sandbox Code Playgroud)
这将转化为:
send(12, "a string", (1, 2, 3), other_object, hostname="localhost", port=8080)
Run Code Online (Sandbox Code Playgroud)
另一个Stack Overflow 问题已经在很大程度上涵盖了这个主题.
\n\n\n我的问题是,为什么?
\n
因为你的 python 语法不允许这样做。它是这样定义的,所以没有真正的“为什么”。
\n\n而且,这是没有必要的。
\n\n"%d %d" % a\n
Run Code Online (Sandbox Code Playgroud)\n\n会工作。
\n\n因此,您需要将扩展转换为元组 \xe2\x80\x93 ,正如 Lafexlos 指出的那样,正确的方法是
\n\n"%d %d" % (*a,)\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
14608 次 |
最近记录: |