将整数元组传递到range()函数

发布于 2025-02-11 22:22:03 字数 576 浏览 1 评论 0原文

我正在尝试检查一个数字是否使用数字间隔

if number in range(2010, 2020)

,但是我想将(2010,2020)存储在带有有意义变量名称的元组中:

VALID_YEARS = (2010, 2020)
if number in range(VALID_YEARS)

返回错误:

TypeError: 'tuple' object cannot be interpreted as an integer

我知道它是可能,

valid_start_year = 2010
valid_end_year = 2020
if number in range(valid_start_year, valid_end_year)

但对我来说,使用元组会更“简洁”。

是否可以?如何?

I'm trying to check if a number is in an interval of numbers using

if number in range(2010, 2020)

However I would like to store (2010, 2020) in a tuple with meaningful variable name:

VALID_YEARS = (2010, 2020)
if number in range(VALID_YEARS)

which returns an error:

TypeError: 'tuple' object cannot be interpreted as an integer

I know it's possible to

valid_start_year = 2010
valid_end_year = 2020
if number in range(valid_start_year, valid_end_year)

but for me using a tuple would be more "concise".

Is it possible? How?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

熟人话多 2025-02-18 22:22:03

您正在寻找拆卸操作员:

VALID_YEARS = (2010, 2020)
number = 2015
if number in range(*VALID_YEARS):
    print('yep')

同样,您也可以解开包装字典作为功能的参数(例如),但是您需要双星:

d = {'a': 1, 'b': 2}


def fun(a, b):
    print(f'{a} and {b}')


fun(**d)

You're looking for the unpacking operator:

VALID_YEARS = (2010, 2020)
number = 2015
if number in range(*VALID_YEARS):
    print('yep')

Similarly, you can also unpack dictionaries to serve as parameters to a function (for example), but you need the double star:

d = {'a': 1, 'b': 2}


def fun(a, b):
    print(f'{a} and {b}')


fun(**d)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文