为什么解包元组会导致语法错误? [英] Why does unpacking a tuple cause a syntax error?

查看:27
本文介绍了为什么解包元组会导致语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,我是这样写的:

bvar=mht.get_value()temp=self.treemodel.insert(iter,0,(mht,False,*bvar))

我试图将 bvar 作为参数扩展到函数调用.但随后它返回:

文件./unobsoluttreemodel.py",第65行temp=self.treemodel.insert(iter,0,(mht,False,*bvar))^语法错误:无效语法

刚刚发生了什么?应该是对的吧?

解决方案

如果要将最后一个参数作为 (mnt, False, bvar[0], bvar[1], ...) 你可以使用

temp = self.treemodel.insert(iter, 0, (mht,False)+tuple(bvar))

<小时>

扩展调用语法*b只能用于调用函数函数参数元组解包在 Python 3.x 上.

<预><代码>>>>def f(a, b, *c): 打印(a, b, c)...>>>x, *y = 范围(6)>>>f(*y)1 2 (3, 4, 5)

元组文字不属于这些情况之一,因此会导致语法错误.

<预><代码>>>>(1, *y)文件",第 1 行SyntaxError:只能使用带星号的表达式作为赋值目标

In Python, I wrote this:

bvar=mht.get_value()
temp=self.treemodel.insert(iter,0,(mht,False,*bvar))

I'm trying to expand bvar to the function call as arguments. But then it returns:

File "./unobsoluttreemodel.py", line 65
    temp=self.treemodel.insert(iter,0,(mht,False,*bvar))
                                                 ^
SyntaxError: invalid syntax

What just happen? It should be correct right?

解决方案

If you want to pass the last argument as a tuple of (mnt, False, bvar[0], bvar[1], ...) you could use

temp = self.treemodel.insert(iter, 0, (mht,False)+tuple(bvar) )


The extended call syntax *b can only be used in calling functions, function arguments, and tuple unpacking on Python 3.x.

>>> def f(a, b, *c): print(a, b, c)
... 
>>> x, *y = range(6)
>>> f(*y)
1 2 (3, 4, 5)

Tuple literal isn't in one of these cases, so it causes a syntax error.

>>> (1, *y)
  File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target

这篇关于为什么解包元组会导致语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆