博客
关于我
python基础知识(3)
阅读量:168 次
发布时间:2019-02-28

本文共 1837 字,大约阅读时间需要 6 分钟。

Python字符串处理与迭代控制

去除字符串首尾空格

去除字符串首尾空格有两种常用方法:

方法一:切片操作

str = ' abcde 'print(str[1:len(str)-1])

方法二:strip()方法

strip()方法可以去除字符串的首尾空格,但不能去除中间空格。

str.strip([chars]);  # 移除字符串头尾指定的字符序列str = "00000003210Runoob01230000000"; print(str.strip('0'));  # 去除首尾字符0str2 = "   Runoob      "; print(str2.strip());  # 去除首尾空格

迭代控制

在Python中,迭代是通过for ... in来完成的。以下是常见迭代对象的操作方法:

字典迭代

d = {'a': 1, 'b': 2, 'c': 3}for key in d:    print(key)# 输出:a b cfor value in d.values():    print(value)# 输出:1 2 3for k, v in d.items():    print(k, v)# 输出:a 1 b 2 c 3

列表迭代

lst = ['acd', 'def', 'ghr']for i in lst:    print(i)# 输出:acd def ghrfor i in range(len(lst)):    print(i)# 输出:0 1 2for item in enumerate(lst):    print(item[0], item[1])# 输出:0 acd 1 def 2 ghr

列表生成式

列表生成式是一种简洁高效的数据生成方式。

生成数列

num_list = list(range(1, 11))print(num_list)# 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

实现阶乘运算

l = []for i in range(1, 11):    l.append(i * i)    print(l)# 输出:# [1]# [1, 4]# [1, 4, 9]# [1, 4, 9, 16]# [1, 4, 9, 16, 25]# [1, 4, 9, 16, 25, 36]# [1, 4, 9, 16, 25, 36, 49]# [1, 4, 9, 16, 25, 36, 49, 64]# [1, 4, 9, 16, 25, 36, 49, 64, 81]# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]l = [i * i for i in range(1, 5)]print(l)# 输出:[1, 4, 9, 16]

高阶函数 - 排序算法

sorted()方法是一个强大的高阶函数,可用于对各种可迭代对象进行排序。

基本用法

sorted_list = sorted([36, 5, -12, 9, -21])print(sorted_list)# 输出:[-21, -12, 5, 9, 36]

自定义排序

sorted_list = sorted([36, 5, -12, 9, -21], key=abs)print(sorted_list)# 输出:[5, 9, -12, -21, 36]

对字符串排序

sorted_str = sorted(['bob', 'about', 'Zoo', 'Credit'])print(sorted_str)# 输出:['about', 'bob', 'Credit', 'Zoo']sorted_str = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)print(sorted_str)# 输出:['about', 'bob', 'Credit', 'Zoo']sorted_str = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)print(sorted_str)# 输出:['Zoo', 'Credit', 'bob', 'about']

通过这些方法,可以轻松地对各种数据进行排序,满足不同场景的需求。

转载地址:http://apnj.baihongyu.com/

你可能感兴趣的文章
Python:从嵌套列表中删除重复项
查看>>
Python:从间隔映射到值
查看>>
Python:使用 shell=False 的子进程调用不起作用
查看>>
Python:修改 PATH 环境变量的平台无关方式
查看>>
Python:假与 0
查看>>
Python:函数使用
查看>>
Python:函数进阶
查看>>
Python:在整数的二进制表示中查找最长的二进制间隙
查看>>
Python:如何从二进制转换为 base 64 并返回?
查看>>
Python:如何以非阻塞方式读取子进程的标准输出
查看>>
Python:如何使用 plotly 制作阴影区域或交替背景颜色?
查看>>
Python:如何根据日期时间获取值的计数
查看>>
python:如何检测串行 COM 上的设备名称/ID
查看>>
Python:如何模拟 datetime.utcnow()?
查看>>
Python:如果DataFrames之间的其他值匹配,则对DataFrame中的值求和
查看>>
Python:字典思维
查看>>
Python:将 HEX 字符串转换为字节
查看>>
Python:将列表与范围列表合并
查看>>
Python:将列表列表初始化为一定大小,
查看>>
Python:带有生成器的给定集合的幂集
查看>>