Python笔记1

2017-05-10  本文已影响0人  小北寻千_QTH

1. list

1.1 reverse a list

lst[::-1]

有返回值,返回一个新的list,原list不变
注:slicing操作都是返回一个新的list

lst.reverse( )

返回None,原list翻转

list(reversed(lst))

返回一个新的list,原list不变
reversed( ) return a "reverse iterator"

1.2 list method

>>> lst = [1,2]
>>> lst.extend([3,4])
>>> lst
[1, 2, 3, 4]
>>> lst.extend((5,6))
>>> lst
[1, 2, 3, 4, 5, 6]

1.3 stack & queue

如果要用queue的话,参考deque

from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") 
>>> queue.append("Graham") 
>>> queue.popleft()
'Eric'
>>> queue.popleft()
 'John'

1.4 Functional Programming Tools

>>> seq = range(8)
>>> def add(x, y): return x+y ...
>>> map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]
>>> def add(x,y): return x+y 
...
>>> reduce(add, range(1, 11)) 
55

2 其他类型

2.1 tuple

2.2 set

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] 
>>> fruit = set(basket) # create a set without duplicates 
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])

2.3 dictionary

操作符

>>> 3.0 // 2 
1.0

floor division: Mathematical division that rounds down to nearest integer.

Strings

>>> print r'C:\some\name'
C:\some\name

在regex时候也常用到

shallow copy & deep copy

to be continued

lambda表达式

to be continued

赋值顺序

a, b = b, a+b

the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

循环

循环中使用else

例子:search for prime numbers

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print n, 'equals', x, '*', n/x
            break
    else:
        print n, 'is prime number'

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

循环技巧

for i, v in enumerate(['a', 'b', 'c']):
    print i, v
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} 
>>> for k, v in knights.iteritems():

参数

def cheeseshop(kind, *arguments, **keywords):
    print kind
    for arg in arguments:
        print arg
    keys = sort(keywords.keys())
    for key in keys:
        print keywords[key]

* : 收集其余位置的参数,如果不提供任何收集的元素,则为空元组,收集的参数存储在tuple中
** : 收集带有关键字的参数,存储在dict中

def parrot(voltage, state='a stiff', action='voom'):
    print "-- This parrot wouldn't", action,
    print "if you put", voltage, "volts through it.",
    print "E's", state, "!"
# 
d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d)
上一篇 下一篇

猜你喜欢

热点阅读