Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.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如果列表中只有一项,则打印一个错误_Python_List - Fatal编程技术网

Python如果列表中只有一项,则打印一个错误

Python如果列表中只有一项,则打印一个错误,python,list,Python,List,我试图编写一些python代码,如果列表中只有一个术语,则会打印一个错误代码 这是我目前的代码: #code to put data into seperate lists inputdata=open("C:\Users\Chloe\Google Drive\Uni\Computing\data.txt", 'r') for datapoint in inputdata: datapoint=datapoint.strip('\n') splitdata=datapoint

我试图编写一些python代码,如果列表中只有一个术语,则会打印一个错误代码

这是我目前的代码:

#code to put data into seperate lists
inputdata=open("C:\Users\Chloe\Google Drive\Uni\Computing\data.txt", 'r')

for datapoint in inputdata:

    datapoint=datapoint.strip('\n')
    splitdata=datapoint.split(',')
    x.append(splitdata[0])
    y.append(splitdata[1])
    e.append(splitdata[2])

#converting data to float in lists
x=[float(i) for i in x]

y=[float(i) for i in y]

e=[float(i) for i in e]  


print ('the x coordinates for the data points are '+str(x))

print ('the y coordinates for the data points are '+str(y))

print ('the associated error for the data points is '+str(e))
当给出正确的数据时,代码就会工作。

您的意思是:

splitdata=datapoint.split(',')
if len(splitdata) != 3:
    print("Wrong number of things")
else:
    x.append(splitdata[0])
    y.append(splitdata[1])
    e.append(splitdata[2])
甚至:

if len(splitdata) != 3:
    raise ValueError("Input data must have three items separated by commas.")

这正是我的意思!但是,每当我在代码中添加此项或类似内容时,它总是打印错误代码,即使我知道列表中的项目数超过了所需的数量,“print splitdata”的输出是什么?@user3552307此测试正好有三个项目,如果您至少需要三个,请更改为
>=3