python進階訓練

來源:互聯網
上載者:User

標籤:result   lte   pytho   too   value   需要   空格   文字格式設定   python   

1、列表,字典,集合解析

from random import randint#列表解析,選出大於0的元素data=[randint(-10,10)for i in range(10)]result1=filter(lambda  x:x>=0 ,data)result2=[x for x in data if x>=0]#最快for x in data:#最慢    if x>=0:        print(x)#字典解析,value大於80d = {x:randint(60,100) for x in (1,20)}#構造字典result3={k:v for k,v in d.items() if v>80}print(result3)#集合解析
#集合中科院被3整除的元素
s=set(data) 
result4={x for x in s if x%3 ==0}

  2、為元組命名

#可命名元組from collections import namedtuple#第一種方式student = (‘BOB‘,16,‘male‘,‘[email protected]‘)name,age,sex,email = range(4)print(student[name])

  

from collections import namedtuple#第一種方式# student = (‘BOB‘,16,‘male‘,‘[email protected]‘)# name,age,sex,email = range(4)# print(student[name])student= namedtuple(‘student‘,[‘name‘,‘age‘,‘sex‘,‘email‘])s=student(‘jim‘,16,‘male‘,‘[email protected]‘)print(s,‘==========‘,s.name)

  執行結果

3、統計序列中元素出現頻度

from random import randintdata = [randint(1,20) for x in range(50)]#隨機序列,計算每個元素出現的次數c=dict.fromkeys(data,0)#0是初始值,將;將列表中的元素作為字典的keyfor x in data:    c[x] +=1

  

from random import randintdata = [randint(1,20) for x in range(50)]#隨機序列,計算每個元素出現的次數from collections import Counterc2  = Counter(data)c2.most_common(3)#哪三個元素出現最多print(c2,c2.most_common(3))

  結果

詞頻統計

import refrom collections import Countertxt = open(‘a.txt‘).read()c1=re.split(‘\w‘,txt)#對非字母進行分割,然後傳進Counterresult = Counter(c1)#將列表傳進去res = result.most_common(3)#出現次數最多的三個單詞

  4、根據字典中值的大小,對字典中的項進行排序

from random import randintd1={x: randint(60,100) for x in ‘abcxyz‘}#六個人分別叫abcxyz#1print(sorted(zip(d1.values(),d1.keys())))#元組組成的列表,比較元組的第一個元素#2print(sorted(d1.items(),key=lambda x :x[1]))

  結果

 

5、如何快速找到多個字典裡面的公用鍵

from random import randint,sample#sample是取樣#1sam=sample(‘abcdef‘,randint(3,6))#隨機選取‘abcdef‘三到6個樣本s1 ={x:randint(1,4) for x in sample(‘abcdef‘,randint(3,6))}s2={x:randint(1,4) for x in sample(‘abcdef‘,randint(3,6))}s3={x:randint(1,4) for x in sample(‘abcdef‘,randint(3,6))}print(s1,s2,s3)for k in s1:    if k in s2 and k in s3:        print(k)

  結果

第二種方法

print(s1.keys() & s2.keys() & s3.keys())#python2是viewkeys,這裡取交集from functools import reduceprint(reduce(lambda a,b:a & b,map(dict.keys,[s1,s2,s3])))#如果鍵多可以這樣,python2是viewkeys

  6,、如何讓字典有序

from collections import  OrderedDictd= OrderedDict()d[‘jib‘]=(1,35)d[‘bob‘]=(2,5)d[‘bbc‘]=(3,5)for i in d:    print(i)

  結果

7、拆分含有多個分隔字元的字串

s=‘ab;cd|efgh|hi,jkl|topq;rst,vww\atex‘t=[]res = s.split(‘;‘)map(lambda x: t.extend(x.split(‘|‘)),res)print(t)

  第二種方法

import res=‘ab;cd|efgh|hi,jkl|topq;rst,vww\atex‘print(re.split(r‘[,;\|]‘,s))

  結果

8、判斷字串開頭

 

 

9、正則調整文字格式設定

import re#1l=[‘2016-05-23‘,‘2016-06-11‘,‘2016-07-12‘]l1=‘2016-05-23‘print(re.sub(‘(\d{4})-(\d{2})-(\d{2})‘,r‘\2/\3/\1‘,l1))

  結果

第二種方法

import re#1l=[‘2016-05-23‘,‘2016-06-11‘,‘2016-07-12‘]l1=‘2016-05-23‘print(re.sub(‘(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})‘,r‘\g<month>/\g<day>/\g<year>‘,l1))

  10、字串拼接

第一種方法

不過這種方法浪費記憶體,下面是第二種方法,用join

11、調節字串置中,左靠右對齊

s= ‘abc‘print(s.ljust(20))print(s.ljust(20,‘+‘))print(s.center(20,‘+‘))

  結果

ling另外一種方法

12、去掉不需要的字串

 去除空格

 

 去除指定字元

s= ‘abc__++++‘print(s.strip(‘_+‘))s1 = ‘abc:1224‘print(s1[:3]+s1[4:])

  結果

s= ‘\tadhi\sfds\sdfds\sdfds\gf\gs\ggg‘print(re.sub(‘[\t\g\f\d]‘,‘‘,s))

  

 

python進階訓練

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.