python 中類型的識別,類型的轉換以及lambda小知識

python新手,以前寫nodejs,java的選手java

python的lambda有點相似nodejs中的arrow function,可是格式可能比較麻煩node

lambda x: x*2 #即一個返回x平方的函數

[ x if x > 3 else -1 for x in range(5) ] #在0到4中選出大於3的數字,若是沒有在缺失位置返回-1

結果[-1,-1,-1,4]

[ x for x in range(5) if x > 3] # 在0到4中返回大於3的數字
結果[4]

這兩個看似很像等其實不一樣。

這種很方便的數組還能夠多重

[ x* y for x in range(4) for y in range(4)]
運行的方式,就是先x的大循環,而後y是它的子循環
結果[0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6]

下面就是關於python類型識別的問題python

對於普通的類型而言,常見的python類型又int,float,str,None,list,dict,datetime之類的,可是咱們如何處理一個由字符串構成的數據的類型呢?數組

name = [None,'123,333',123.33,'444.44','678','{"123456","567"}']
#一個由各類類型數據混合而成的數組,咱們目標是統計各類類型的數據的次數
#先來一個檢驗類型的函數
def jtype(data):
'''
識別數據的類型
@data 數組數據
'''

if type(data) == str:
    if data == '':
        types[type(None)] += 1
        return type(None)
    elif data.startswith('{'):
        return type([])
    else:
        try:
            int(data)
            return type(1)
        except ValueError as e:
            try:
                float(data)
                return type(1.1)
            except ValueError as e:
                return type('')
    return types
else:
    return type(data)

首先經過type ==str 咱們能夠判斷當前的類型是不是咱們須要轉換的字符串類型,若是是,進行咱們的類型判斷,先進行的None空類型的判斷,順序挺重要,先進行空判斷再進行其餘步驟不然如下的問題都會出異常就沒意義了。其次進行的是數組的判斷,這邊就不寫字典了,方法差很少,這邊定義以'{'開頭的的數據爲數組。若是是咱們再進行其餘的判斷。到了數字類型的話要先進行int的判斷,再到float,都不行就是str了。函數

def count_type(data_set):
from collections import defaultdict 

types = defaultdict(int)
for dp in data_set:
    types[jtype(dp)] += 1
return types
#得出結果 defaultdict(<type 'int'>, {<type 'list'>: 1, <type 'float'>: 2, <type 'str'>: 1, <type 'NoneType'>: 1, <type 'type'>: 1})

if type(int) == int:
    print 'same'
elif type(1) == int:
    print 'same 2'
else:
    print 'no both'

結果輝縣市same 2,由於int自己是type類型,type(int)結果仍是typecode

相關文章
相關標籤/搜索