Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x python函数从用户处读取输入行并返回_Python 3.x_Pandas - Fatal编程技术网

Python 3.x python函数从用户处读取输入行并返回

Python 3.x python函数从用户处读取输入行并返回,python-3.x,pandas,Python 3.x,Pandas,我试图编写一个函数,从用户那里读取输入行,直到用户按下Enter键。每行应首先包含索引,然后包含相应的值,并用空格分隔。这些索引和值将在函数中用于返回一个系列。格式错误的输入应导致异常。输入行的格式不正确,如果它不是空的,并且以空格分隔时,不会导致两部分。我的函数看起来: 运行该函数会出现以下错误: 我无法理解res有两个元素,为什么res[1]会出现错误。有人可以帮我节省时间。您应该使用索引器,而不是错误消息中指出的ValueError 您还应该首先尝试获取值。如果没有,则当您在没有空

我试图编写一个函数,从用户那里读取输入行,直到用户按下Enter键。每行应首先包含索引,然后包含相应的值,并用空格分隔。这些索引和值将在函数中用于返回一个系列。格式错误的输入应导致异常。输入行的格式不正确,如果它不是空的,并且以空格分隔时,不会导致两部分。我的函数看起来:



运行该函数会出现以下错误:




我无法理解res有两个元素,为什么res[1]会出现错误。有人可以帮我节省时间。

您应该使用
索引器,而不是错误消息中指出的
ValueError

您还应该首先尝试获取值。如果没有,则当您在没有空格的情况下输入时,索引的长度与值的长度不同,因此无法创建
系列

def read_series():
val=[]
ind=[]
尽管如此:
x=输入(“给出系列的索引和值(按空格分隔):”)
res=x.split(“”)
尝试:
val.append(res[1])
ind.append(res[0])
除索引器外:
打破
返回pd.系列(val,索引=ind)
def read_series():
    val = []
    ind = []
    while True:
        x = input("Give index and value for the series(sep by whitespace): ")

        try:
            res = x.split(' ')
            ind.append(res[0])
            val.append(res[1])
        except ValueError:
            break
    return pd.Series(val, index=ind)
val.append(res[1])
IndexError: list index out of range