Python 程序按标点符号数量对字符串进行排序
pythonserver side programmingprogramming更新于 2025/10/14 16:44:17
当需要按标点符号数量对字符串进行排序时,会定义一个方法,该方法以字符串为参数,使用列表推导和‘in’运算符来确定结果。
下面是相同的演示 −
示例
from string import punctuation
def get_punctuation_count(my_str):
return len([element for element in my_str if element in punctuation])
my_list = ["python@%^", "is", "fun!", "to@#r", "@#$learn!"]
print("列表为:")
print(my_list)
my_list.sort(key = get_punctuation_count)
print("结果为:")
print(my_list)
输出
列表为: ['python@%^', 'is', 'fun!', 'to@#r', '@#$learn!'] 结果为: ['is', 'fun!', 'to@#r', 'python@%^', '@#$learn!']
解释
将所需的包导入到环境中。
定义了一个名为‘get_punctuation_count’的方法,该方法以字符串为参数,并使用列表推导式遍历元素。
它检查字符串是否包含标点符号。
它返回包含标点符号的字符串的长度作为输出。
在方法之外,定义一个列表并显示在控制台上。
使用‘sort’方法对列表进行排序,并将键指定为先前定义的方法。
这是显示在控制台上的输出。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

