《Head First Python》學習筆記 Chapter5:數(shù)據(jù)處理

本章的目的是學習簡單的數(shù)據(jù)處理,首先給出了一些文本數(shù)據(jù),需要將這些文本數(shù)據(jù)讀取,并轉換為列表,然后對列表中的數(shù)據(jù)進行統(tǒng)一格式化,最后進行排序。

本章所需的數(shù)據(jù)獲取地址:獲取數(shù)據(jù)

數(shù)據(jù)處理

未優(yōu)化的代碼

# 對時間字符串進行格式化,統(tǒng)一形式為mins.secs
def sanitize(time_string):
    if '-' in time_string:
           splitter = '-'
    elif ':' in time_string:
        splitter = ':'
    else:
        return(time_string)
    (mins, secs) = time_string.split(splitter)
    return(mins + '.' + secs)

# 讀取文件,并將記錄時間轉換成列表
with open('james.txt') as jaf:
    data = jaf.readline()
james = data.strip().split(',')

with open('julie.txt') as juf:
    data = juf.readline()
julie = data.strip().split(',')

with open('mikey.txt') as mif:
    data = mif.readline()
mikey = data.strip().split(',')

with open('sarah.txt') as saf:
    data = saf.readline()
sarah = data.strip().split(',')

clean_james = []
clean_julie = []
clean_mikey = []
clean_sarah = []

---------臃腫的部分------------
for each_t in james:
    clean_james.append(sanitize(each_t))

for each_t in julie:
    clean_julie.append(sanitize(each_t))

for each_t in mikey:
    clean_mikey.append(sanitize(each_t))

for each_t in sarah:
    clean_sarah.append(sanitize(each_t))

print(sorted(clean_james))
print(sorted(clean_julie))
print(sorted(clean_mikey))
print(sorted(clean_sarah))
---------臃腫的部分------------

優(yōu)化的代碼

def sanitize(time_str):
    if '-' in time_str:
        spliter = '-'
    elif ':' in time_str:
        spliter = ':'
    else:
        return time_str
    (mins, secs) = time_str.split(spliter)
    return(mins + '.' + secs)

# 將讀取文件的代碼抽取成函數(shù)
def get_coach_data(filename):
    try:
        with open(filename) as file:
            data = file.readline();
        return data.strip().split(',')
    except IOError as err:
        print('File error:' + str(err))
        return None

# 去除列表中的重復數(shù)據(jù)
def clean_data(data):
    clean_data = []
    for item in data:
        if item not in clean_data:
            clean_data.append(item)
    return clean_data

james = get_coach_data('james.txt')
julie = get_coach_data('julie.txt')
mikey = get_coach_data('mikey.txt')
sarah = get_coach_data('sarah.txt')

james_format = [sanitize(data) for data in james]
julie_format = [sanitize(data) for data in julie]
mikey_format = [sanitize(data) for data in mikey]
sarah_format = [sanitize(data) for data in sarah]

clean_james = clean_data(james_format)
clean_julie = clean_data(julie_format)
clean_mikey = clean_data(mikey_format)
clean_sarah = clean_data(sarah_format)

print(sorted(clean_james)[0:3])
print(sorted(clean_julie)[0:3])
print(sorted(clean_mikey)[0:3])
print(sorted(clean_sarah)[0:3])

兩種排序方法

原地排序(In-place sorting):data.sort()

該方法會對排列數(shù)據(jù)(data)按指定的順序進行排序,然后用排好順序的數(shù)據(jù)替換掉原有的數(shù)據(jù),因此原有的數(shù)據(jù)順序會丟失。

復制排序(Copied sorting):sorted(data)

對數(shù)據(jù)按指定的順序進行排序,然后返回原數(shù)據(jù)的一個有序副本。原數(shù)據(jù)依然保留,只是對副本進行排序

>>> data = [6,3,1,2,5,4]
>>> data
[6, 3, 1, 2, 5, 4]


>>> data.sort() # 對數(shù)據(jù)進行原地排序
>>> data
[1, 2, 3, 4, 5, 6] # 原數(shù)據(jù)的順已經改變
>>> 
>>> data = [6,3,1,2,5,4]
>>> data_sort = sorted(data) # 對數(shù)據(jù)進行復制排序,返回一個有序副本
>>> data
[6, 3, 1, 2, 5, 4] # 原數(shù)據(jù)順序仍然存在


>>> data_sort
[1, 2, 3, 4, 5, 6]

列表推導式(list comprehension)

使用方法

[表達式 for 變量 in 列表] 或者 [表達式 for 變量 in 列表 if 條件]

使用示例

# 將分鐘數(shù)轉化成秒數(shù)
>>> mins = [1,2,3]
>>> secs = [m * 60 for m in mins]
>>> secs
[60, 120, 180]

# 求列表中數(shù)字的平方
>>> data = [1,2,3,4]
>>> data_square = [num * num for num in data]
>>> data_square
[1, 4, 9, 16]

# 還可以跟其他條件,對列表中的數(shù)據(jù)進行篩選處理
>>> result = [num * 2 for num in data if num > 2]
>>> result
[6, 8]

# 也可以增加更多的for語句的部分:
>>> result = [[x,y] for x in range(2) for y in range(2)]
>>> result
[[0, 0], [0, 1], [1, 0], [1, 1]]
>>> 

Set:無序、不可重復

初始化

1.創(chuàng)建一個空的set

distances = set()

2.為set提供一個數(shù)據(jù)列表(需要用大括號包圍

>>> distances = {10.6,11,8,10.6,"two",7}
>>> distances
{8, 10.6, 11, 'two', 7} # 自動過濾掉了重復的數(shù)據(jù)

3.為set指定一個現(xiàn)有的列表

>>> list = [2,2,3,5,6]
>>> distances = set(list)
>>> distances
{2, 3, 5, 6}

零碎知識點

list列表分片

列表分片主要用于獲取列表的一個子部分,即通過L[x:y]取得并返回列表L在偏移量x到y(tǒng)(包括x不包括y)之間的一個新列表,如下所示:

>>> [1,2,3,4,5,6][2:5]
[3, 4, 5]

另外,如果偏移量留空,則第一個偏移量默認為列表的頭部,第二個默認為末尾:

>>> [1,2,3,4,5,6][:]
[1, 2, 3, 4, 5, 6]

如果這樣做,相當于對原列表做一個淺拷貝。

分片實際還接收第三個參數(shù),其代表步長,默認情況下,該值為1。下面將步長改為2:

>>> [1,2,3,4,5,6][::2]
[1, 3, 5]

如果把步長設為負值會有什么效果呢?

>>> [1,2,3,4,5,6][::-2]
[6, 4, 2]

相當于反轉了列表,從列表的尾部開始遍歷。

工廠函數(shù)

工廠函數(shù)用于創(chuàng)建某種類型的新的數(shù)據(jù)項,例如set()就是一個工廠函數(shù),因為它會創(chuàng)建一個新的集合。


如果覺得有用,歡迎關注我的微信,有問題可以直接交流:

你的關注是對我最大的鼓勵!
你的關注是對我最大的鼓勵!
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 個人學習批處理的初衷來源于實際工作;在某個迭代版本有個BS(安卓手游模擬器)大需求,從而在測試過程中就重復涉及到...
    Luckykailiu閱讀 5,001評論 0 11
  • 國家電網公司企業(yè)標準(Q/GDW)- 面向對象的用電信息數(shù)據(jù)交換協(xié)議 - 報批稿:20170802 前言: 排版 ...
    庭說閱讀 12,537評論 6 13
  • 一、實驗目的 學習使用 weka 中的常用分類器,完成數(shù)據(jù)分類任務。 二、實驗內容 了解 weka 中 explo...
    yigoh閱讀 8,870評論 5 4
  • 斑駁的印痕至今還清晰的留在那里,磚墻上你的名字依舊還在。那殘陽如血映紅了半邊天,如今我們都四散而去。外面的世界雖說...
    _Dtath閱讀 395評論 0 2
  • 房價已經高過天了,不過它還是如雨后春筍,一路高歌猛進。 高到了什么程度呢,高到一個普通人需要二三十年不吃不喝才能擁...
    致遠投資黃紹國閱讀 354評論 0 0

友情鏈接更多精彩內容