Python 条件和循环学习笔记(一)

来源:互联网 发布:淘宝网mp3 编辑:程序博客网 时间:2024/06/10 08:48

一、众所周知, 使用映射对象(比如字典)的一个最大好处就是它的搜索操作比类似 if-elif-else
语句或是 for 循环这样的序列查询要快很多.:

   if user.cmd == 'create':
action = "create item"
elif user.cmd == 'delete':
action = 'delete item'
elif user.cmd == 'update':
action = 'update item'
else:
action = 'invalid choice... try again!'

 

上面的语句完全可以满足我们的需要, 不过我们还可以用序列和成员关系操作符来简化它:
if user.cmd in ('create', 'delete', 'update'):
action = '%s item' % user.cmd
else:
Edit By Vheavens
Edit By Vheavens
action = 'invalid choice... try again!'

 

另外我们可以用 Python 字典给出更加优雅的解决方案.
msgs = {'create': 'create item',
'delete': 'delete item',
'update': 'update item'}
default = 'invalid choice... try again!'
action = msgs.get(user.cmd, default)

 

 

二.简单的三元操作符

>>> x, y = 4, 3
>>> if x < y:
... smaller = x
... else:
... smaller = y
...
>>> smaller

3

在 2.5 以前的版本中, Python 程序员最多这样做(其实是一个 hack ):
>>> smaller = (x < y and [x] or [y])[0]
>>> smaller
3

 

在 2.5 和更新的版本中, 你可以使用更简明的条件表达式:
>>>Smaller= x if x<y else y

>>>Smaller

3

 

三、系统函数 range()

Python 提供了两种不同的方法来调用 range() . 完整语法要求提供两个或三个整数参数:
range(start, end, step =1)
range() 会返回一个包含所有 k 的列表, 这里 start <= k < end , 从 start 到 end , k 每

递增 step . step 不可以为零,否则将发生错误.
>>> range(2, 19, 3)
[2, 5, 8, 11, 14, 17]
如果只给定两个参数,而省略 step, step 就使用默认值 1 .
>>> range(3, 7)
[3, 4, 5, 6]

 

xrange() 类似 range() , 不过当你有一个很大的范围列表时, xrange() 可能更为适合, 因为
它不会在内存里创建列表的完整拷贝. 它只被用在 for 循环中, 在 for 循环外使用它没有意义。