1. 程式人生 > >python 資料使用小技巧

python 資料使用小技巧

一,從列表中 中篩選資料
例如:獲取集合中大於某個條件的數

lists = [-1,-2,-4,-5,-6,0,1,4,9]
# 找出大於0的數
str = []
for number in lists:
    if number > 0:
        str.append(number)
print(str)
#[1, 4, 9]

#列表式
str = [x for x in lists if x >0]
print(str)

#Pyhton2.7 返回列表,Python3.x 返回迭代器物件,即物件再可以轉化位列表
newStr = filter(lambda x: x >0,lists)
print(list(newStr))

二:對元組中每個元素重新命名,獲取其值
例如:

name = 0
age = 1
sex = 2
number = 3

#定義變數取代列表中的索引值
lists = ("yuanyang","19","nan","139")
#利用lists[name]取代lists[0]
print(lists[name])
#yuanyang


#利用標準庫中的namedtuple對元組重新命名
from collections import namedtuple
student = namedtuple("students",["name","age","sex","number"])
str = student("zhangsan","20","nan","9898")
print(str)
#students(name='zhangsan', age='20', sex='nan', number='9898')
print(str.name)
#zhangsan

三:統計序列中 元素出現的頻率
例如:

list = [12,5,6,4,6,5,5,7,8,4,3,1,2,6]
#根據key生成一個新的字典
str = dict.fromkeys(list,0)
print(str)
#{12: 0, 5: 0, 6: 0, 4: 0, 7: 0, 8: 0, 3: 0, 1: 0, 2: 0}
for number in list:
    str[number] += 1
print(str)
#{12: 1, 5: 3, 6: 3, 4: 2, 7: 1, 8: 1, 3: 1, 1: 1, 2: 1}


#利用標準庫中的Counter來統計資料
from collections import Counter
#找到每個字母出現的次數
newStr = Counter(list)
print(newStr)
#Counter({5: 3, 6: 3, 4: 2, 12: 1, 7: 1, 8: 1, 3: 1, 1: 1, 2: 1})
#出現頻率最高的3位
counterStr = newStr.most_common(3)
print(counterStr)
#[(5, 3), (6, 3), (4, 2)]

四:根據字典中值的大小,對字典的項排序
例如:

from random import randint
#建立一個字典
str = {x: randint(60,100) for x in "xyzabc"}
#{'x': 96, 'y': 94, 'z': 76, 'a': 79, 'b': 88, 'c': 60}
print(str)
#將字典轉化為一個新的元組
newStr = zip(str.values(),str.keys())
#sorted 預設是對key值進行排序
print(sorted(newStr))
#[(60, 'b'), (67, 'y'), (69, 'x'), (69, 'z'), (78, 'c'), (94, 'a')]


#第2種方式 通過自定義規格排序規則
newSortStr = sorted(str.items(),key=lambda x:x[1])
print(newSortStr)

五:查詢字典中出現的公共鍵
例如:

from random import randint,sample
#從多個字典中提取出公共的鍵的元素
#sample(序列a,n)
#功能:從序列a中隨機抽取n個元素,並將n個元素生以list形式返回。

str = sample("abcdefg",randint(3,6))
print(str)
#['f', 'a', 'd', 'g', 'b']
s1 = {x: randint(1,4)for x in str}
print(s1)
#{'a': 4, 'c': 2, 'e': 4}
s2 = {x: randint(3,6)for x in str}
s3 = {x: randint(4,7)for x in str}
newduple = []
for x in s1:
    if x in s2 and x in s3:
        newduple.append(x)
print(newduple)

#第2種方式
dict1.viewkeys()&dict2.viewkeys()&dict3.viewkeys() 這個前提是需要知道哪些字典參與

#第3種方式
 map(dict.viewkeys,[dict1,dict2,dict3]) 求得字典的viewkeys集合
 print reduce(func,map(dict.viewkeys,[dict1,dict2,dict3])) 通過求交集的方式求得公共鍵

六:讓字典保持有序
例如:

from collections import OrderedDict
#得到一個有序的空字典
dicts = OrderedDict()
dicts["angle"] = (1,90)
dicts["dimu"] = (3,78)
dicts["baby"] = (2,80)
for x in dicts:
     print(x)

七:實現使用者的歷史記錄功能
例如:

#標準庫collections 中的duque,是一個雙端迴圈佇列
from collections import deque
#新的佇列中 只保留最近出現的3個數據
newList = deque([],3)
newList.append(1)
newList.append(2)
newList.append(3)
print(newList)
#eque([1, 2, 3], maxlen=3)

八,列表的反向迭代
例如:

lists = [1,2,3,4,5]
newList = lists[::-1]
print(newList)
#[5, 4, 3, 2, 1]

#list.reverse() 該方法沒有返回值,但是會對列表的元素進行反向排序。
lists.reverse()
print(lists)
#[5, 4, 3, 2, 1]

#reversed返回的是一個迭代器物件的記憶體地址
str = reversed(lists)
print(list(str))
#[5, 4, 3, 2, 1]
'''

九:for迴圈迭代多個可迭代物件
例如:並行迭代  序列迭代
#利用zip將多個可迭代物件合併 每次迭代返回一個元組 並行迭代
chinese = [1,2,3,4]
math = [6,2,3,4]
englist = [1,8,3,4]
total = []
for c,m,e in zip(chinese,math,englist):
    total.append(c+m+e)
print(total)
#[8, 12, 9, 12]

#序列迭代 使用標準庫中的itertools.chain 它能將多個可迭代物件連線
from  itertools import chain
for s in chain(chinese,math,englist):
    if s >5:
        print(s)
        #6,8