我这里有一些代码意味着允许我继续创建浮点数,直到我输入0使其停止(然后删除0)。这些浮点数应该输入到列表中。我遇到的问题是每次运行while循环时,都会覆盖float_list。
again = True
float_count = 1
while (again):
float_list = [float(input("Float%d: " % i))for i in range(float_count, float_count + 1)]
last_float = float_list[-1]
if (last_float == 0):
again = False
del float_list[-1]
else:
float_count = float_count + 1
有没有办法改变这段代码所以所有浮点数都输入到列表中?谢谢!
答案 0 :(得分:2)
这可能是使用iter(fn, sentinel)
的替代形式的一个很好的选择,例如:
float_list = [float(x) for x in iter(input, '0')]
如果您需要提示,则可以创建辅助函数:
import itertools as it
fc = it.count(1)
float_list = [float(x) for x in iter(lambda: input('Float{}: '.format(next(fc))), '0')]
或者(最接近匹配OP的尝试 - 将退出0
,0.0
,0.00
等):
fc = it.count(1)
float_list = list(iter(lambda: float(input('Float{}: '.format(next(fc)))), 0.0))
有错误处理:
def get_float():
fc = it.count(1)
def _inner():
n = next(fc)
while True:
try:
return float(input("Float{}: ".format(n)))
except ValueError as e:
print(e)
return _inner
float_list = list(iter(get_float(), 0.0))
答案 1 :(得分:1)
列表理解在这里真的不合适。更简单:
float_count = 1
float_list = []
while True:
val = input("Float%d: " % float_count)
if val == '0':
break
float_list.append(float(val)) # call float(val) to convert from string to float
float_count += 1
如果用户没有键入浮点数,那么对于不崩溃可能更加用户友好,例如:
def read_float(msg):
while 1:
val = input(msg)
if val == '0':
return val
try:
return float(val)
except ValueError:
print("%s is not a float, please try again.." % val)
def read_float_list():
float_count = 1
float_list = []
while True:
val = read_float("Float%d: " % float_count)
if val == '0':
break
float_list.append(val) # now val has been converted to float by read_float.
float_count += 1