1. 程式人生 > >9.20作業

9.20作業

lose 元素 查找 速度 pen 表示 span rose spa

總結列表,元組,字典,集合的聯系與區別:

列表,元組,字典,集合的聯系與區別:列表,元組是有順序的,而字典和集合是沒順序的。列表是以[ ]形式表示,元組是以( )表示,字典以{ }表示,集合則是以[()]的形式表示。列表是可變對象,可以有增刪改操作,而元組是只讀的,不能修改。字典使用鍵-值(key-value)存儲,鍵是不可變的對象。插入和查找速度快,不會隨著鍵的增加而變慢,需要占用大量的內存。字典是用空間換取時間的一種方法。集合是一個無序不重復元素集, 基本功能包括關系測試和消除重復元素。

列表,元組,字典,集合的遍歷:

列表是可變序列,元組是不可變序列;列表的值可以修改,而元祖的值初始化後不可修改,兩者都是有序的。字典和集合 兩者都是無序的,數據量大時可用集合或列表來創建
a = list(457451)      #列表的遍歷
print(a)
for i in a:
    print(i)

b = tuple(485890)       #元組的遍歷
print(b)
for i in b:
    print(i)

c = set(256156)        #集合的遍歷
print(c)
for i in c:
    print(i)

d = {bob:80,rose:79,jack:90}        #字典的遍歷
print(d)
for i in d:
    print(i,d[i])

技術分享圖片

英文詞頻統計:

  • 下載一首英文的歌詞或文章str
  • 分隔出一個一個的單詞 list
  • 統計每個單詞出現的次數 dict
strgc=‘‘‘
Oh, nowhere left to go.
Are we getting closer
No. All we know is No.
Nights are getting colder, colder
Hey. Tears all fall the same.
We all feel the rain.
We can‘t change.
Everywhere we go, we‘re looking for the sun.
Nowhere to grow old. We‘re always on the run.
They say we‘ll rot in hell, but I don‘t think we will.
They‘ve branded us enough. Outlaws of love.
Scars make us who we are.
Hearts and homes are broken, broken.
Far, we could go so far,with our minds wide open, open.
Hey. Tears all fall the same.
We all feel the rain.
We can‘t change.
Everywhere we go, we‘re looking for the sun.
Nowhere to grow old. We‘re always on the run.
They say we‘ll rot in hell, but I don‘t think we will.
They‘ve branded us enough. Outlaws of love.
Outlaws of love.
‘‘‘ strgc = strgc.replace(., ) strList = strgc.split() print(len(strList),strList) #分隔一個一個單詞並統計英文單詞個數 strSet = set(strList) #將列表轉化成集合,再將集合轉化成字典來統計每個單詞出現次數 print(strSet) strDict={} for word in strSet: strDict[word] = strList.count(word) print(len(strDict),strDict)

技術分享圖片

9.20作業