Python stackoverflow

Python stackoverflow#

1. 基本問題##

1.1 判斷一個list 是否爲空###

連接 --> 地址html

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

對於元組,字典,字符串對象均可以這麼操做,會顯得 quite pythonicpython

1.2 怎麼給一個字典排序###

連接 -- > 地址git

排序通常都是使用python的內置函數 sortedapp

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

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

其中: cmpkey參數都是函數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)) # 這個能夠按照第二列排序

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會取得一個或多個序列爲參數,而後返回元組的列表,將這些序列中的並排的元素配成對。使用方法以下:

相關文章
相關標籤/搜索