根据可能值列表检查值

时间:2016-10-18 20:48:04

标签: python list

我需要检查列表长度的东西。也许是这样的,但这不起作用:

if len(list) != 1 or 2:
   # Do something

if len(list) == 1 or 2:
   # Do something different

好的,我自己想出来了:

if len(list) == 1:
   # Do something
elif len(list) == 2:
   # Do the same something

if len(list) != 2:
   # Do something different
elif len(list) != 1:
   # Do something different

1 个答案:

答案 0 :(得分:3)

这样的东西
if 1 <= len(list) <= 2:
    ...

或:

if len(list) in (1, 2):
    ...

应该有效