我试图在一个将用户输入附加到列表中的函数中使用列表作为参数
itemno, itemdescrip, itempr = [], [], []
def inpt(x):
n=0
while n < 10:
n+=1
x.append(int(input("What is the item number?")))
inpt(*itemno)
print(itemno)
当我在函数中输入1但得到错误时我期望输出为1:TypeError:inpt()缺少1个必需的位置参数:'x'
%cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:itemno, itemdescrip, itempr = [], [], []
:
:def inpt(x):
:
: n=0
: while n < 10:
: n+=1
: x.append(int(input("What is the item number?")))
:
:
:inpt(itemno)
:print(itemno)
:--
What is the item number? 1
What is the item number? 2
What is the item number? 3
What is the item number? 4
What is the item number? 5
What is the item number? 6
What is the item number? 7
What is the item number? 8
What is the item number? 9
What is the item number? 10
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
你只需要从函数调用中删除“*”
当你在一个函数调用中使用*
为序列添加前缀时,你告诉unpack这个序列;也就是说,将序列的每个成员作为函数的单个参数。在你的代码中:
inpt(*itemno)
由于itemno
是空的,你告诉它解压缩到函数参数中。因此,该函数调用相当于:
inpt()
由于你的inpt()
函数需要一个参数,它会引发错误。我不确定为什么你认为*
是必需的,但简单的解决方法是删除它,它将列表本身传递给函数:
inpt(itemno)