資料結構相關模組(列表)

來源:互聯網
上載者:User

標籤:python   運算式   record   字串   產生器   

所有內容參照自 python cookbook

1.解壓序列賦值給多個變數 一般來講我們賦值變數是這樣:

a = 1

python可以這樣:

a,b = 1,2

或者這樣:

e=[1,2,3,4]a,b,c,d=e

當然 你想解壓幾層就解壓幾層,比如這樣:

data = [ ‘ACME‘, 50, 91.1, (2012, 12, 21) ]name, shares, price, (year, mon, day) = data

如果你只是想要其中的幾個變數,這。。。。python沒有給出特別的方式,你可以用一些不常用的變數名去佔位。 比如:

data = [ ‘ACME‘, 50, 91.1, (2012, 12, 21) ]_, shares, price, _ = data

雖然說是列表解析 ,但同樣適用於字串,檔案對象,迭代器,產生器

s = ‘hello‘a,b,c,d,e = s

有時候迭代對象的元素會超過變數個數,那該怎麼辦 ,這時候就要用到星號運算式了

record = (‘Dave‘, ‘[email protected]‘, ‘773-555-1212‘, ‘847-555-1212‘)name, email, *phone_numbers = record

解壓出來的phone_numbers永遠是列表,即使沒有元素,當然,更常見的是把星號運算式做為參數 比如:

def add(*args):    n=0    for i in args:        n+=i    return n

然後我們就可以傳任意個參數給add函數了~

add(1,2,3)add(5,1,2,6,7)
2.序列中出現次數最多的元素

collections.Counter類就是專門為這類問題設計的,並用一個most_common()方法直接給出答案

words = [‘look‘, ‘into‘, ‘my‘, ‘eyes‘, ‘look‘, ‘into‘, ‘my‘, ‘eyes‘,‘the‘, ‘eyes‘, ‘the‘, ‘eyes‘, ‘the‘, ‘eyes‘, ‘not‘, ‘around‘, ‘the‘,‘eyes‘, "don‘t", ‘look‘, ‘around‘, ‘the‘, ‘eyes‘, ‘look‘, ‘into‘,‘my‘, ‘eyes‘, "you‘re", ‘under‘]from collections import Counterword_counts = Counter(words)top_three = word_counts.most_common(3)(print(top_three)# Outputs [(‘eyes‘, 8), (‘the‘, 5), (‘look‘, 4)]

在底層實現上,一個 Counter 對象就是一個字典,將元素映射到它出現的次數上。比如:

>>> word_counts[‘not‘]1

並且可以手動增加計數

word_counts[‘not‘]+=1

Counter執行個體可以進行數學運算操作


本文出自 “機制小風風” 部落格,請務必保留此出處http://xiaofengfeng.blog.51cto.com/8193303/1885778

資料結構相關模組(列表)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.