小编pyt*_*ies的帖子

如何针对2个可能的值检查变量?

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

s = 'a'
Run Code Online (Sandbox Code Playgroud)

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

if s == 'a' or s == 'b':
   return 1
elif s == 'c' or s == 'd':
   return 2
else: 
   return 3
Run Code Online (Sandbox Code Playgroud)

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

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

if s == 'a' or 'b':
   ...
Run Code Online (Sandbox Code Playgroud)

显然这不起作用,对我来说相当愚蠢.

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

return 1 if s == 'a' or s == 'b' ...
Run Code Online (Sandbox Code Playgroud)

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

python

20
推荐指数
2
解决办法
2万
查看次数

标签 统计

python ×1