Python - 输入浮点参数列表

时间:2016-08-16 17:09:24

标签: python file floating-point

我在脚本中从用户那里获取浮点参数并想知道是否有更好/更有效的方式,包括如果用户只提供一个参数(或根本没有)的选项,有什么方法我默认剩下的两个为0.0?并且可能是存储在文件中的更好方法

#inside a loop to keep getting values         
line = raw_input("Enter three parm values: ")
x=line.split(' ')
fa=fb=fc=0.0 

a=x[0]
b=x[1] #what if user only supplies only one?
c=x[2] # how can i leave this or default to 0.0?

fa=float(a)
fb=float(b)
fc=float(c)

file=open(inputFile, 'a+')
file.write(name)
file.write("\t")
file.write(a)
file.write(" ")
file.write(b)
file.write(" ")
file.write(c)
file.write("/n")

4 个答案:

答案 0 :(得分:3)

为什么不使用列表来保存任意数量的变量?

floats = [float(var) if var else 0. 
          for var in raw_input("Enter three parm values: ").split(' ')]
with open(inputFile, 'a+') as f:
    f.write(name + '\t' + ' '.join(str(f) for f in floats) + '\n')

如果你想用额外的零填充这个列表最多三个参数,那么你可以这样做:

floats = [1]  # For example.
if len(floats) < 3:
    floats += [0] * (3 - len(floats))

>>> floats
[1, 0, 0]

答案 1 :(得分:2)

更新以解决索引超出范围错误:

# use python ternary operator to set default value
# index goes out of range
#c = x[2] if x[2] is not None else 0
# use array length instead
b = x[1] if len(x) >= 2 else 0
c = x[2] if len(x) >= 3 else 0

file=open(inputFile, 'a+')
# string concatenation gets rid of repeated function calls
file.write(name + "\t" + a + " " + b + " " + c + "\n")

答案 2 :(得分:1)

你可以检查line.split(&#39;&#39;)返回的列表的长度,看看你有多少,然后从那里开始。或者您可以在分配之前检查列表中的条目是否为“无”。

对于写入文件,最好的办法是设置数据的结构,然后只调用一次write,因为这会阻碍你在文件I / O中的效率。

答案 3 :(得分:1)

#use length of list for checking the input and continue with your operation
line = raw_input("Enter three parm values: ")
x=line.split(' ')
a=b=c=0
fa=fb=fc=0.0 
listLen = len(x)
if(listLen == 3):
    a, b, c = x[0], x[1], x[2]
elif(listLen == 2):
    a, b = x[0], x[1]
elif(listLen == 1):
    a = x[0]