improve your python code(9)

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:2


print("Beijing" in s)   # output: true

res = 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 string
print(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
   the
Tian'anmen
  Square
    of
   the
 Capital
 Beijing.
左对齐
I
like
the
Tian'anmen
Square
of
the
Capital
Beijing.
0填充
0000I
0like
00the
Tian'anmen
Square
000of
Capital
Beijing.
"""

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:带一个参数的函数,用于提取每个元素的比较值,默认为None
reverse:表示结果是否反转
"""

"""
先按照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}]
None

sorted会返回一个排序后的列表,原有的列表不变
而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}]
"""










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值