简体   繁体   English

如何以pythonic的方式做到这一点?

[英]How to do this in a pythonic way?

Consider this Python snippet: 考虑以下Python代码段:

for a in range(10):

    if a == 7:
        pass
    if a == 8:
        pass
    if a == 9:
        pass
    else:
        print "yes"

How can it be written shorter? 怎么写得更短?

#Like this or...
if a ?????[7,8,9]:
    pass

Use the in operator: 使用in运算符:

if a in (7,8,9):
    pass

To test if a falls within a range: 要测试a是否在范围内:

if 7 <= a <= 9:
  pass

To test if a is in a given sequence: 要测试a是否在给定的序列中:

if a in [3, 5, 42]:
  pass
for a in range(10):
    if a > 6:
        continue
    print('yes')

Based on your original code the direct "pythonic" replacement is: 根据您的原始代码,直接的“ pythonic”替换为:

if not a in [7, 8, 9]:
     print 'yes'

or 要么

if a not in [7, 8, 9]:
     print 'yes'

The latter reads a little better, so I guess it's a bit more "pythonic". 后者的读取效果更好,所以我想它有点“ pythonic”。

if a in [7,8,9]

Depending on what you want to do, the map() function can also be interesting: 根据您想做什么, map()函数也可能很有趣:

def _print(x):
    print 'yes'

map(_print, [a for a in range(10) if a not in (7,8,9)])

What about using lambda. 怎么样使用lambda。

>>> f = lambda x: x not in (7, 8, 9) and print('yes')
>>> f(3)
yes
>>> f(7)
False

Since the question is tagged as beginner, I'm going to add some basic if-statement advice: 由于该问题被标记为初学者,因此我将添加一些基本的if语句建议:

 if a == 7: pass if a == 8: pass if a == 9: ... else: ... 

are three independent if statements and the first two have no effect, the else refers only to 是三个独立的if语句,前两个无效,否则else仅指

  if a == 9: 

so if a is 7 or 8, the program prints "yes". 因此,如果a为7或8,程序将输出“是”。 For future use of if-else statement like this, make sure to use elif: 为了将来使用类似这样的if-else语句,请确保使用elif:

if a == 7:
    seven()
elif a == 8:
    eight()
elif a == 9:
    nine()
else:
    print "yes"

or use just one if-statement if they call for the same action: 或如果他们要求相同的动作,则仅使用一个if语句:

if a == 7 or a == 8 or a == 9:
    seven_eight_or_nine()
else:
    print "yes"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM