【问题标题】:How do I access the value of a parameter in the range() function from within a loop?如何从循环中访问 range() 函数中的参数值?
【发布时间】:2019-09-06 16:33:07
【问题描述】:

我想从 for 循环中访问 range() 函数的参数值。我目前有以下工作代码:

import inflect

start = 0
stop = 5
step = 2

o = inflect.engine()

for i in range(start, stop, step):
    print(f"{i} is the {o.number_to_words(o.ordinal((i + step) // step))} "
          f"value when counting from {start} to {stop} by {step}")

产生以下所需的输出:

0 is the first value when counting from 0 to 5 by 2
2 is the second value when counting from 0 to 5 by 2
4 is the third value when counting from 0 to 5 by 2

我想要一种无需先定义startstopstep 即可生成相同输出的方法。我设想的解决方案类似于:

import inflect

o = inflect.engine()

for i in range(0, 5, 2):
    start = range.getparameters[0]
    stop = range.getparameters[1]
    step = range.getparameters[2]

    print(f"{i} is the {o.number_to_words(o.ordinal((i + step) // step))} "
          f"value when counting from {start} to {stop} by {step}")

【问题讨论】:

    标签: python function for-loop parameters range


    【解决方案1】:

    字段与参数同名:

    r = range(1, 10, 2)
    print(r.start, r.stop, r.step)
    

    请注意,这需要在 for 循环之前将范围分配给变量。或者,如果您使用的是 Python 3.8,则可以使用赋值表达式。

    【讨论】:

    • 关于赋值表达式的绝妙花絮。我正在运行 3.7,但这是我升级的一个令人信服的理由。
    猜你喜欢
    • 2021-07-12
    • 2017-05-09
    • 2015-09-19
    • 1970-01-01
    • 2021-02-19
    • 2020-07-14
    • 2021-02-09
    • 2020-06-17
    • 1970-01-01
    相关资源
    最近更新 更多