If you cant explain it simply, you dont understand it well enough

Python stackoverflow

Python stackoverflow#

1. 基本问题##

1.1 判断一个list 是否为空###

链接 --> 地址

>>> a = []
>>> if not a:
... 	print "empty"

对于元组,字典,字符串对象都可以这么操作,会显得 quite pythonic

1.2 怎么给一个字典排序###

链接 -- > 地址

排序一般都是使用python的内置函数 sorted

>>> help(sorted)
Help on built-in function sorted in module __builtin__:

sorted(...)
	sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

其中: cmpkey参数都是函数

sorted函数会默认对字典的key排序,并且输出排序后key的list

>>> a
{1: 3, 2: 2, 3: 1}
>>> sorted(a)
[1, 2, 3]

输入a.items()默认会以字典的key排序

>>> sorted(a.items())
[(1, 3), (2, 2), (3, 1)]

那么怎么以第二列,或者第三列排序呢?

方法1:

>>> from operator import itemgetter
>>> sorted(a.items(), key = itemgetter(1))
[(3, 1), (2, 2), (1, 3)]

其中: itemgetter 是operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号)。例如:

>>> 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)) # 这个可以按照第二列排序

1.3 产生固定长度的由字母和数字组成的随机字符串###

链接 -- > 地址

通过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 就可以实现了。

1.4 *args and **kwargs###

链接 -- > 地址

一个星和两个星分别是什么:

>>> 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)

1.5 python中并行遍历多个list###

内置的zip函数可以让我们使用for循环来并行使用多个序列。在基本运算中,zip会取得一个或多个序列为参数,然后返回元组的列表,将这些序列中的并排的元素配成对。使用方法如下:

posted @ 2016-08-09 20:22  zk47  阅读(440)  评论(0编辑  收藏  举报

I am a stupid bird, and I need to work hard