在Python中,使用' elif'之间的区别是什么?陈述与'或'声明?

时间:2014-12-03 17:26:34

标签: python

两种选择有何不同?我使用一些任意代码作为例子,但问题是一般的。

使用'或'

if (passenger['Sex'] == 'female') or (passenger['Pclass'] == 1):
    predictions[passenger_id] = 1
else:
    predictions[passenger_id] = 0

使用' elif'

if (passenger['Sex'] == 'female'):
    predictions[passenger_id] = 1
elif (predictions[passenger_id] = 1):
    predictions[passenger_id] = 1
else:
    predictions[passenger_id] = 0

4 个答案:

答案 0 :(得分:4)

第一个减少代码重复。例如

s = 'd'
if s == 'a' or s == 'b' or s == 'c'... etc:
    print('Is alpha')
else:
    print('Not alpha')

相反
s = 'd'
if s == 'a':
    print('Is alpha')  # repetition of same code
elif s == 'b':
    print('Is alpha')  # repetition of same code
elif s == 'c':
    print('Is alpha')  # repetition of same code
elif... etc:
    print('Is alpha')  # repetition of same code
else:
    print('Not alpha')

请注意,以上只是一个示例来说明问题,你可以更加诡异地做

if s.isalpha():

if s in string.ascii_lowercase:

答案 1 :(得分:1)

在您的代码段中,没有功能性区别(在if-suite的末尾,您将获得相同的结果)。但是,or允许您只在分支中编写一次更干的代码(不要重复自己) - 而且这几乎总是一件好事。

在一般情况下,elif允许您在不同的分支中执行不同的操作:

if (passenger['Sex'] == 'female'):
    do_thing_1()
elif (predictions['Pclass'] = 1):
    do_thing_2()

这不能使用or完成。

答案 2 :(得分:1)

如果您希望某些代码在前一条款为elif并且此条件为False且未重新评估或重新指定<的条件下运行,则使用True / strong>那个早期的条款。假设我们想根据他们的分数给某人评分。我们可以这样写:

if score >= 90:
    grade = 'A'
if score < 90 and score >= 80: # not using: 80 <= score < 90, to make AND explicit
    grade = 'B'
if score < 80 and score >= 70:
    grade = 'C'
if score < 70 and score >= 60:
    grade = 'D'
else:
    grade = 'E'

如您所见,我们重复相同的信息。如果我们想要获得A,你需要至少95分,我们必须记住将90改为95两次,或者面对有趣的错误。

使用elif你可以像这样重写它:

if score >= 90:
    grade = 'A'
elif score >= 80: # implicit condition: score < 90
    grade = 'B'
elif score >= 70: # implicit conditions: score < 90 and score < 80
    grade = 'C'
elif score >= 60: # implicit conditions: score < 90 and score < 80 and score < 70
    grade = 'D'
else:
    grade = 'E'

如果你在这里使用if而不是elif,那么每个至少有60分的人都会获得D.只使用or也不会有效:

if score >= 90 or score >= 80 or score >= 70 or score >= 60:
    grade = '?'

因此,是否使用elif在很大程度上取决于条件之间的相似性以及True时需要运行的代码之间的相似性。

在你的情况下,第一个选项更好,因为你并不真正关心这两个条件中的哪一个True;在这两种情况下都需要发生这种情况。

答案 3 :(得分:0)

基于mgilson的问题,elif使用多个分支,而or语句一次评估everythin(貌似)。在

的情况下
if a or b:

如果'b'的评估时间要比'a'长得多,那么最好使用'elif'。

if a:
  {code}
elif b:
  {code}
else:
  {other code}

此处'b'仅在发现'a'为假时进行评估,因此节省了处理时间。

注意:我将使用C,C ++和basic的经验。如果python与'或'语句的处理方式不同,请告诉我。