连接 --> 地址html
>>> a = [] >>> if not a: ... print "empty"
对于元组,字典,字符串对象均可以这么操做,会显得 quite pythonicpython
连接 -- > 地址git
排序通常都是使用python的内置函数 sorted
app
>>> help(sorted) Help on built-in function sorted in module __builtin__: sorted(...) sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
其中: cmp
和key
参数都是函数dom
sorted
函数会默认对字典的key排序,而且输出排序后key的list函数
>>> a {1: 3, 2: 2, 3: 1} >>> sorted(a) [1, 2, 3]
输入a.items()
默认会以字典的key排序ui
>>> sorted(a.items()) [(1, 3), (2, 2), (3, 1)]
那么怎么以第二列,或者第三列排序呢?spa
方法1:code
>>> from operator import itemgetter >>> sorted(a.items(), key = itemgetter(1)) [(3, 1), (2, 2), (1, 3)]
其中: itemgetter 是operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即须要获取的数据在对象中的序号)。例如:orm
>>> g1 = itemgetter(2) # 定义一个函数,获取输入的第三维值 >>> c = [1,2,3] >>> g1(c) 3
方法2:
>>> sorted(a.items(), key = lambda x : x[1]) [(3, 1), (2, 2), (1, 3)]
给List排序:
>>> import operator >>> L = [] >>> L.sort() # 默认是按照第一列排序 >>> L.sort(key = operator.itemgetter(2)) # 这个能够按照第二列排序
连接 -- > 地址
经过random.choice()
来实现
>>> import string >>> import random >>> def id_generator(size = 6, chars = string.ascii_letters + string.digits): ... return ''.join(random.choice(chars) for _ in range(size)) ... >>> id_generator() 'AOkD5t'
具体怎么实现的?
>>> string.ascii_letters 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> string.digits '0123456789'
string
的用法能够参考:python string docs, 后面的join
也是string
库提供的方法
>>> help(string.join) Help on function join in module string: join(words, sep=' ') join(list [,sep]) -> string Return a string composed of the words in list, with intervening occurrences of sep. The default separator is a single space. (joinfields and join are synonymous)
再经过获取随机数 + 列表推导 + join 就能够实现了。
连接 -- > 地址
一个星和两个星分别是什么:
>>> def test_para(*args, **kwargs): ... print type(args) ... print type(kwargs) ... >>> test_para() <type 'tuple'> <type 'dict'>
在定义函数的时候,当咱们不知道须要输入几个参数的时候,能够用*args
来实现:
>>> def test_para(*args): ... for count, thing in enumerate(args): ... print '{0} . {1}'.format(count, thing) ... >>> test_para('apple', 'banana', 'cabbage') 0 . apple 1 . banana 2 . cabbage
当在test_para
函数中,添加一个变量a
>>> def test_para(a, *args): ... for count, thing in enumerate(args): ... print '{0} . {1}'.format(count, thing) ... print a ... >>> test_para('apple', 'banana', 'cabbage') 0 . banana 1 . cabbage apple
注意 1:确切命名的变量,只能放在前面,*args只能放在最后
>>> def test_para(*args, a): File "<stdin>", line 1 def test_para(*args, a): ^ SyntaxError: invalid syntax
**kwargs 用于处理没有定义的name = value
,这种类型的参数
>>> def test_kwargs(**kwargs): ... for k, v in kwargs.items(): ... print '{0} = {1}'.format(k, v) ... >>> test_kwargs(k1 = 'v1', k2 = 'v2') k2 = v2 k1 = v1
注意 2: 命名的参数,只能放在**kwargs前面
注意 3: 同一个函数定义中能够同时有*args和**kwargs,可是*args必须在**kwargs的前面,所以标准的定义的为:
>>> def test_para(..., *args, **kwargs)
内置的zip函数能够让咱们使用for循环来并行使用多个序列。在基本运算中,zip会取得一个或多个序列为参数,而后返回元组的列表,将这些序列中的并排的元素配成对。使用方法以下: