python 編程技巧(一)

如何在字典,列表,集合中 篩選數(shù)據(jù)

運行在ipython中

常規(guī) filter 列表解析

# 如何在列表,字典,集合中根據(jù)條件篩選數(shù)據(jù)?
from random import randint

# 常規(guī)
data = [1, 2, 34, 56, -1]
x = []
for v in data:
    if v > 0:
        x.append(v)
print(x)

# filter
data = [randint(-10, 10) for _ in range(10)]
timeit filter(lambda x: x >= 0, data)

#列表解析
timeit ([x for x in data if x>= 0])

#對于字典篩除某些元素
d={x:randint(60,100) for x in range(1,21)}
{for k,v in d.items() if v >90}

#集合篩選 data 是上面的數(shù)據(jù)
s = set(data)
{for x in s if s % 3 ==0 and s!=0}

如何為元組中的每個元素命名,提高程序可讀性

以學(xué)生信息 為例


student = ('jim',16,'male','x@x.com')
#name
student[0]
#age
student[1]
#sex
student[2]
#可讀性很差  所以我們可以使用
name,age,sex,email = range(4)
這樣我們插敘 就可以使用
student[name]  #可讀性就高了

還可以利用namedtuple

from collections import namedtuple
Student = namedtuple('Student',['name','age','sex',email'])
s = Student('jim',16,'male','x@x.com')
s2 = Student(name='jim',age=16,sex='male',email='x@x.com')
#name
s.name
#age
s.age
isinstance(s,tuple) #他們兩個是一個類型

這里是使用了 collections 中的namedtuple 命名元組
這樣也行

如何統(tǒng)計序列中的元素的出現(xiàn)額度?

dict.fromkeys()

from random import randint
data = [randint(20) for _ in range(30)]
#創(chuàng)建字典  使用data中的每一個元素作為key 值為0
c = dict.fromkeys(data,0) 
for x in data:
    c[x] +=1
#遍歷data中所有的值 然后 每遇到一個值 就在c[x]中進行加一

如果要查詢 出現(xiàn)頻率最高的值 我們就可以使用更好的方法

Counter and most_common

from collections import Counter
c2 = Counter (data)  #也是一個字典 但是它直接做了 c的事,直接做了詞頻統(tǒng)計   c2 跟c 是一樣的
c2.most_common(3)  #出現(xiàn)頻率最高的三個元素 非常簡單好用

文本文件 詞頻統(tǒng)計

#在網(wǎng)上隨便找一篇 英文文章 保存本地來使用
from collections import Counter
import re
txt = open('son.txt'),read()
c3 = Counter(re.split('\W',txt))  #進行頻率統(tǒng)計
c3.most_common(10)  #查詢最高頻率的十個單詞

對字典進行排序

方法1 sorted

#對學(xué)生成績進行排序  字典 對應(yīng)一個學(xué)生名 一個成績
from random import randint
s = {x:randint(60,100) for x in range('xyzabc')}  #這樣就得到了6個小朋友的成績
#使用sorted排序  如果直接使用sorted
sorted(s) #那么只會比較  xyzabc 這些 不會比較 后面的成績
#因此我們需要 把 字典變?yōu)樵M  (95,‘a(chǎn)’) 這樣的形式 就可以進行比較了 
#使用zip方法
c = zip(d.values(),d.keys())  #如果不成功就在zip 前面加上 list()  同樣在py2 中可以使用itervalues來更好
sorted(c) #這樣就進行排序了

方法二 sorted key的用法

s.items() #直接得到 元組 但是 這個元組是 ('a',95) 名字在前 所以我們還需要 sorted中有一個key方法
sorted(s.items(),key= lambda x:x[1])  #這里的x[1] 就是比較 元組索引位  1 的值 就是 成績
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容