better way than using if

Possible Duplicate:
Putting a simple if-then statement on one line

I am working on a python expression and I want that expression to be compressed than using the if else statement.

s = [1, 2, 3, 4]
if len(s)>5:
    print s.index(5)
else:
    print 'cant print'

Is there a better way than using as if else statement?


You can do:

s = [1, 2, 3, 4]
print 'y' if len(s) > 5 else 'n'

However I don't think this makes the code more readable (at a glance). Also note that if and else don't create a loop, they are simply statements for control flow. Loops are written using for and while .


Short, but very obfuscated (don't do this):

print 'ny'[len(s) > 5]

[edit] the reason you should never do this, is because it uses properties of the language that are little known to most people, ie that bool is a subclass of int. In most situations where you find yourself writing code like the OP, it's usually better to create a flag variable

s_is_long = len(s) > 5

then you can use any of the more appropriate ways to write the print, eg:

print 'y' if s_is_long else 'n'

or

print {True: 'y', False: 'n'}[s_is_long]

or the most readable of all...

if s_is_long:
    print 'y'
else:
    print 'n'

在这种情况下,您可以使用try / except块:

try:
    print s.index(5)
except ValueError:
    print "5 not in list"
链接地址: http://www.djcxy.com/p/42718.html

上一篇: 注释掉一个Python代码块

下一篇: 比使用if更好的方法