【问题标题】:Entering floats into a list without overwriting list将浮点数输入列表而不覆盖列表
【发布时间】:2017-06-14 08:19:13
【问题描述】:

我这里有一些代码允许我继续创建浮点数,直到我输入 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

有没有办法改变这段代码,让所有的浮点数都输入一个列表?谢谢!

【问题讨论】:

  • while循环外初始化float_list并在循环内使用float_list.extend
  • 没想到,谢谢!

标签: python python-3.x


【解决方案1】:

这可能是使用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 的尝试 - 将在 00.00.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))

【讨论】:

  • 感谢您的回答!
  • 您能否将0.(浮点值零)添加到列表中?
  • @thebjorn 在前 2 个 sn-ps 中是的,在最后 2 个中没有,但足够简单,可以在必要时添加该处理。不是 OP 明确要求的,OP 的原始代码也会在 '0.' 上停止。
  • 很公平,我会给你一个开箱即用的解决方案(开箱即用的方法;-)
【解决方案2】:

列表推导式在这里确实不合适。简单得多:

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

【讨论】:

  • 谢谢!这正是我一直在寻找的。出于某种原因,稍后在我的代码中使用它时出现错误。我正在使用 itertools 从列表中生成组合,如下所示:for c in itertools.combinations(float_list, 10): average = sum(c)/10 但我得到:average = sum(c)/10 TypeError: unsupported operand type(s) for +: 'int' and 'str '。有任何想法吗?谢谢!
  • 我认为这是因为列表是['.1', '.2', '.3', '.4', '.5', '.6', '.7', '.8', '.9', '.8', '.7', '.6', '.5', '.5', '.5', '.6', '.7'] 而之前是[.1, .2, .3, .4, .5, .6, .7, .8, .9, .8, .7, .6, .5, .5, .5, .6, .7] 有没有办法让列表看起来像以前?
  • 对不起,我忘记了 Python 3 改变了 input 函数的语义。我已经修复了代码。
  • 我能够弄清楚:)。关于从列表中删除撇号的任何想法?
  • 只看到 val == 0 被更改为 val == '0'。你帮了我很多,谢谢伙计!
猜你喜欢
  • 2016-06-14
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多