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

时间:2014-04-19 18:13:29

标签: 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.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))

当给出正确的数据时,代码可以工作。

1 个答案:

答案 0 :(得分:1)

你的意思是:

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.")