improve your python code(9)__python

來源:互聯網
上載者:User
1. 字串處理小結
#!/usr/bin/env python# encoding: utf-8"""@python version: python3.6.1@author: XiangguoSun@contact: sunxiangguodut@qq.com@site: http://blog.csdn.net/github_36326955@software: PyCharm@file: strmethod.py@time: 5/7/2017 12:45 PM""""""字串操作"""s = "   I like   the Tian'anmen Square    of the Capital Beijing.  "print(s.count('the'))   # output:2print("Beijing" in s)   # output: trueres = s.replace('.', '!')print(s, "| ", res)"""output:   I like   the Tian'anmen Square    of the Capital Beijing.   |     I like   the Tian'anmen Square    of the Capital Beijing!"""pre, key, post = s.partition("Tian'anmen Square")print(pre,"|",key,"|",post)"""output:   I like   the  | Tian'anmen Square |     of the Capital Beijing."""print(s.split())print(s.split(" "))"""output:['I', 'like', 'the', "Tian'anmen", 'Square', 'of', 'the', 'Capital', 'Beijing.']['', '', '', 'I', 'like', '', '', 'the', "Tian'anmen", 'Square', '', '', '', 'of', 'the', 'Capital', 'Beijing.', '', '']"""print(s.title())import stringprint(string.capwords(s))"""output:   I Like   The Tian'Anmen Square    Of The Capital Beijing.I Like The Tian'anmen Square Of The Capital Beijing."""word_list = s.split()print("置中對齊:")for word in word_list:    print(word.center(10))print("靠左對齊")for word in word_list:    print(word.ljust(10))print("0填充")for word in word_list:    print(word.zfill(5))"""output:置中對齊:    I   like   theTian'anmen  Square    of   the Capital Beijing.靠左對齊IliketheTian'anmenSquareoftheCapitalBeijing.0填充0000I0like00theTian'anmenSquare000ofCapitalBeijing."""print(s)print(s.strip())"""output:   I like   the Tian'anmen Square    of the Capital Beijing.I like   the Tian'anmen Square    of the Capital Beijing."""print(s)print(" ".join(s.split()))"""output:   I like   the Tian'anmen Square    of the Capital Beijing.I like the Tian'anmen Square of the Capital Beijing."""
2.operator.itemgetter函數

operator模組提供的itemgetter函數用於擷取對象的哪些維的資料,參數為一些序號(即需要擷取的資料在對象中的序號),如若你用過padas、numpy的話,相信你對這個概念會理解。相當於那裡的axis。下面看例子。

a = [1,2,3] b=operator.itemgetter(1)     #定義函數b,擷取對象的第1個域的b(a) 2 b=operator.itemgetter(1,0)   #定義函數b,擷取對象的第1個域和第0個的值b(a) (2, 1)

用 operator 函數進行多級排序

students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]  sorted(students, key=itemgetter(1,2))"""sort by grade then by age"""  [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]  

對字典排序

d = {'data1':3, 'data2':1, 'data3':2, 'data4':4}  sorted(d.iteritems(), key=itemgetter(1), reverse=True)  [('data4', 4), ('data1', 3), ('data3', 2), ('data2', 1)]
3. sort與sorted
persons = [{'name':'Bon','age':32},           {'name':'Alan','age':50},           {'name':'Bon','age':33},           {'name':'Job','age':23}]"""sort與sorted原型:sorted(iterable[,cmp[,key[,reverse]]])s.sort([cmp[,key[,reverse]]])cmp:比較函數key:帶一個參數的函數,用於提取每個元素的比較值,預設為Nonereverse:表示結果是否反轉""""""先按照name有小到大排序。對於name相同的,則按照age有小到大排序"""print(sorted(persons, key = lambda x:(x['name'],x['age'])))print(persons)persons.sort(key = lambda x:(x['name'],x['age']))print(persons)print(persons.sort(key = lambda x:(x['name'],x['age'])))"""output[{'name': 'Alan', 'age': 50}, {'name': 'Bon', 'age': 32}, {'name': 'Bon', 'age': 33}, {'name': 'Job', 'age': 23}][{'name': 'Bon', 'age': 32}, {'name': 'Alan', 'age': 50}, {'name': 'Bon', 'age': 33}, {'name': 'Job', 'age': 23}][{'name': 'Alan', 'age': 50}, {'name': 'Bon', 'age': 32}, {'name': 'Bon', 'age': 33}, {'name': 'Job', 'age': 23}]Nonesorted會返回一個排序後的列表,原有的列表不變而sort會直接修改原有列表,函數返回None.""""""sorted()作用於任意可迭代對象,而sort一般作用於列表:"""a_tuple = (1,2,4,2,3)# print(a_tuple.sort()) # 報錯print(sorted(a_tuple))    # 正確 [1, 2, 2, 3, 4]from operator import itemgetter"""對字典排序:"""phonebook = {'Linda':'7750','Bob':'9345','Carol':'5834'}sorted_pb = sorted(phonebook, key=itemgetter(1))    # 按照數字大小進行排序print(sorted_pb)"""多維list排序:"""gameresult = [['Bob',95,'A'],['Alan',86,'C'],['Mandy',82,'A'],['Rob',86,'E']]print(sorted(gameresult,key=itemgetter(2,1)))from operator import itemgetter"""字典中混合list"""mydic = {'Li':['M',7],         'Lh':['M',6],         'Zhang':['E',2],         'Wang':['P',3],         'Du':['C',9],         'Ma':['C',2],         'Zhe':['H',7]    }"""下面的k=('Li':['M',7])"""print(sorted(mydic.items(),key=itemgetter(0)))      # 按照'Li'排序print(sorted(mydic.items(),key=lambda k:itemgetter(1)(k[1])))   # 按照7排序print(sorted(mydic.items(),key=lambda k:itemgetter(0)(k[1])))   # 按照'M'排序"""output:[('Du', ['C', 9]), ('Lh', ['M', 6]), ('Li', ['M', 7]), ('Ma', ['C', 2]), ('Wang', ['P', 3]), ('Zhang', ['E', 2]), ('Zhe', ['H', 7])][('Zhang', ['E', 2]), ('Ma', ['C', 2]), ('Wang', ['P', 3]), ('Lh', ['M', 6]), ('Li', ['M', 7]), ('Zhe', ['H', 7]), ('Du', ['C', 9])][('Du', ['C', 9]), ('Ma', ['C', 2]), ('Zhang', ['E', 2]), ('Zhe', ['H', 7]), ('Li', ['M', 7]), ('Lh', ['M', 6]), ('Wang', ['P', 3])]""""""list中混合字典;"""game = [{'name':'a','grade':2},{'name':'b','grade':1}]print(sorted(game,key=itemgetter('grade')))"""output:[{'name': 'b', 'grade': 1}, {'name': 'a', 'grade': 2}]"""

聯繫我們

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