如何根据 2 个可能的值检查变量? [英] How to check variable against 2 possible values?

查看:34
本文介绍了如何根据 2 个可能的值检查变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一个字母字符串的变量 s

I have a variable s which contains a one letter string

s = 'a'

根据那个变量的值,我想返回不同的东西.到目前为止,我正在做一些类似的事情:

Depending on the value of that variable, I want to return different things. So far I am doing something along the lines of this:

if s == 'a' or s == 'b':
   return 1
elif s == 'c' or s == 'd':
   return 2
else: 
   return 3

有没有更好的方法来写这个?更Pythonic的方式?或者这是最有效的?

Is there a better way to write this? A more Pythonic way? Or is this the most efficient?

以前,我错误地有这样的事情:

Previously, I incorrectly had something like this:

if s == 'a' or 'b':
   ...

显然这行不通,而且我很愚蠢.

Obviously that doesn't work and was pretty dumb of me.

我知道条件赋值并尝试过这个:

I know of conditional assignment and have tried this:

return 1 if s == 'a' or s == 'b' ...

我想我的问题特别是有没有一种方法可以将变量与两个值进行比较,而无需键入something == something or something == something

I guess my question is specifically to is there a way you can compare a variable to two values without having to type something == something or something == something

推荐答案

if s in ('a', 'b'):
    return 1
elif s in ('c', 'd'):
    return 2
else:
    return 3

这篇关于如何根据 2 个可能的值检查变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆