收藏一些python的小技能

例子1:For .. else 语法

foo=[2,1]
for i in foo: 
    if i == 0: 
        break 

else: print("i was never 0")

例子2:for in 输出索引

>>> a = ['a', 'b', 'c', 'd', 'e']
>>> for index, item in enumerate(a): print index, item
...
0 a
1 b
2 c
3 d
4 e
>>>

例子3:string 分割函数

cars = ['Red_sedan', 'Big_truck', 'Small_roadster']
for car in cars:
    head, sep, tail = car.partition('_')
    print tail
>>>Red _ sedan
>>>Big _ truck
>>>Small _ roadster

例子4: python键值对转换

>>> a_dict = {'a': 1, 'b': 2, 'c': 3} 
>>> {value:key for key, value in a_dict.items()} 
{1: 'a', 2: 'b', 3: 'c'}

转自:http://www.codeday.top/2016/09/26/265.html

posted @ 2016-09-27 13:55  编程笔记  阅读(212)  评论(0编辑  收藏  举报