improve your python code(9)

本文介绍了Python中的字符串处理方法,包括计数、查找、替换等,并详细解释了字符串的多种格式化方式。此外,还深入探讨了Python中的排序方法,包括使用sorted()函数和list.sort()方法的不同之处,以及如何利用operator模块中的itemgetter函数进行多级排序。

1. 字符串处理小结

#!/usr/bin/env python
# encoding: utf-8


"""
@python version: python3.6.1
@author: XiangguoSun
@contact: sunxiangguodut@qq.com
@site: http://blog.youkuaiyun.com/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}]
"""










### Python Code Examples for Expressing Love Certainly! Below are some creative and thoughtful ways to express love through Python code: #### Simple Heart Shape Using Print Statements A straightforward way to show affection is by printing a heart shape. ```python print(" *** ") print(" ***** *****") print(" *********** ") print("*** ***") print("* *") ``` This creates a visual representation of a heart using asterisks[^1]. #### Personalized Message Generator Creating personalized messages can add an extra layer of sentimentality. ```python def generate_love_message(name): message = f"Dear {name},\n\nYou mean the world to me." return message partner_name = "Alice" print(generate_love_message(partner_name)) ``` The function `generate_love_message` takes a name as input and returns a heartfelt message directed at that person[^2]. #### Interactive Love Calculator (for Fun) An interactive program where users can enter their names along with their partner's name to get a fun score indicating compatibility. ```python import random def calculate_love_score(your_name, partner_name): combined_names = your_name + partner_name score = sum(ord(char.lower()) - ord('a') + 1 for char in combined_names if char.isalpha()) final_score = score % 100 + 1 return min(final_score, 100) your_name = input("Enter your name: ").strip() partner_name = input("Enter your partner's name: ").strip() score = calculate_love_score(your_name, partner_name) print(f"\nThe love score between you and {partner_name} is {score}%!") if score >= 85: print("That’s incredibly high! True love might be found here.") elif score >= 60: print("It looks promising!") else: print("Keep nurturing this relationship; it has potential.") ``` In this script, user inputs two names which then go into calculating a pseudo-love percentage based on character values from ASCII codes. The result provides playful feedback about the likelihood of true love existing between those named individuals[^3]. --related questions-- 1. How do I modify these scripts to include more personal details? 2. Can such programs help improve communication within relationships? 3. What other types of symbolic patterns could one create using Python print statements besides hearts? 4. Is there any library specifically designed for generating romantic content via programming languages like Python?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值