python3字符串处理,高效切片

高级技巧:切片,迭代,列表,生成器

切片

L = ['Hello', 'World', '!']print("-------1.一个一个取-------")
print(L[0])
print(L[1])
print(L[2])print("-------2.开辟一个新列表把内容存进去-------")
r = []
for i in range(3):r.append(L[i])print(r)print("-------3.切片操作-------")
print("L[0:3]", L[0:3])
print("L[:3]", L[:3])
print("L[1:3]", L[1:3])
print("L[-1]", L[-1])
print("L[-2:]", L[-2:])
print("L[-2:-1]", L[-2:-1])print("_____________切片操作详解——————————————————————")
L = list(range(1, 100))
print(L)print(L[:10])
print(L[5:10])
print(L[-10])
print(L[-10:])
print(L[:-80])
print(L[10:-80])print("前10个数每隔2个取一个")
print(L[::])
print(L[:10:2])
print("所有数每隔5个取一个")
print(L[::5])print("一个例题,把字符串前后的空格删除")
def trim(s):length = len(s) - 1if length < 0:return ''last = lengthwhile s[ length ] == ' ' :length -= 1last = lengthif length < 0:return ''first = 0while s[first] == ' ':first += 1last += 1l = s[first:last]return lif trim('hello  ') != 'hello':print('测试失败!')
elif trim('  hello') != 'hello':print('测试失败!')
elif trim('  hello  ') != 'hello':print('测试失败!')
elif trim('  hello  world  ') != 'hello  world':print('测试失败!')
elif trim('    ') != '':print('测试失败!')
elif trim('') != '':print('测试失败!')
else:print('测试成功!')print("一个例题,查找最大数,最小数")
def findMinAndMax(L):if len(L) == 0:return None, Nonemax, min = L[0], L[0]for i in L:if min > i:min = iif max < i:max = ireturn min, maxif findMinAndMax([]) != (None, None):print('测试失败!')
elif findMinAndMax([7]) != (7, 7):print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):print('测试失败!')
else:print('测试成功!')
  • 切片的几个例子
def trim(s):length = len(s) - 1if length < 0:return ''last = lengthwhile s[ length ] == ' ' :length -= 1last = lengthif length < 0:return ''first = 0while s[first] == ' ':first += 1last += 1l = s[first:last]return lif trim('hello  ') != 'hello':print('测试失败!')
elif trim('  hello') != 'hello':print('测试失败!')
elif trim('  hello  ') != 'hello':print('测试失败!')
elif trim('  hello  world  ') != 'hello  world':print('测试失败!')
elif trim('    ') != '':print('测试失败!')
elif trim('') != '':print('测试失败!')
else:print('测试成功!')def findMinAndMax(L):if len(L) == 0:return None, Nonemax, min = L[0], L[0]for i in L:if min > i:min = iif max < i:max = ireturn min, maxif findMinAndMax([]) != (None, None):print('测试失败!')
elif findMinAndMax([7]) != (7, 7):print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):print('测试失败!')
else:print('测试成功!')print("一个例题,取出字符,并全部转换为小写")L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L if isinstance(s, str)]
print(L2)# 测试:
print(L2)
if L2 == ['hello', 'world', 'apple']:print('测试通过!')
else:print('测试失败!')

生成器

生成器详解

g = (x * x for x in range(1, 10))for i in g:print(i)
  • 生成器特点
print("generator的函数,在每次调用next()的时候执行,""遇到yield语句返回,再次执行时从上次返回的yield语句""处继续执行。")def odd():print('step 1')yield 1print('step 2')yield(3)print('step 3')yield(5)o = odd()
print(next(o))
print(next(o))
print(next(o))
  • 应用:打印杨辉三角
print("----------------------------------------------------")
print("杨辉三角打印")def triangles():L = [1]while True:yield LL = [1] + [L[i - 1] + L[i] for i in range(1, len(L))] + [1]n = 0
results = []
for t in triangles():print(t)results.append(t)n = n + 1if n == 10:break

用filter求素数

计算素数的一个方法是埃氏筛法,它的算法理解起来非常简单:

首先,列出从2开始的所有自然数,构造一个序列:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …

取序列的第一个数2,它一定是素数,然后用2把序列的2的倍数筛掉:

3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …

取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉:

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …

取新序列的第一个数5,然后用5把序列的5的倍数筛掉:

7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …

不断筛下去,就可以得到所有的素数。

用Python来实现这个算法,可以先构造一个从3开始的奇数序列:

def _odd_iter():n = 1while True:n = n + 2yield n

注意这是一个生成器,并且是一个无限序列。

然后定义一个筛选函数:

def _not_divisible(n):return lambda x: x % n > 0
最后,定义一个生成器,不断返回下一个素数:def primes():yield 2it = _odd_iter() # 初始序列while True:n = next(it) # 返回序列的第一个数yield nit = filter(_not_divisible(n), it) # 构造新序列

这个生成器先返回第一个素数2,然后,利用filter()不断产生筛选后的新的序列。

由于primes()也是一个无限序列,所以调用时需要设置一个退出循环的条件:

# 打印1000以内的素数:

for n in primes():if n < 1000:print(n)else:break

注意到Iterator是惰性计算的序列,所以我们可以用Python表示“全体自然数”,“全体素数”这样的序列,而代码非常简洁。

特殊函数

  • 传入函数
def add(x, y, f):return f(x) + f(y)x = -5
y = 6
f = absprint(add(x, y, f))
  • map

def f(x):return x * x
r = list(map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]))print(r)

输出结果

[1, 4, 9, 16, 25, 36, 49, 64, 81]Process finished with exit code 0
  • reduce
from functools import reducedef mul(x, y):return x * y
def prod(L):return reduce(mul, [1, 3, 5, 7, 9])print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:print('测试成功!')
else:print('测试失败!')
  • 一个应用
    字符串转整形
print("字符串转整形")
from functools import reduce
def fn(x, y):return x * 10 + ydef char2num(s):digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}return digits[s]L = reduce(fn, map(char2num, '13579'))
print(isinstance(L,int))

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/382500.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

linux线程学习初步02

杀死线程的函数 int pthread_cancel(pthread_t thread); 参数介绍&#xff1a;需要输入的tid 返回值&#xff1a;识别返回 errno成功返回 0 被杀死的线程&#xff0c;退出状态值为一个 #define PTHREAD_CANCELED((void *)-1)代码案例&#xff1a; #include <stdio.h> #…

python的文件基本操作和文件指针

读写模式的基本操作 https://www.cnblogs.com/c-x-m/articles/7756498.html r,w,a r只读模式【默认模式&#xff0c;文件必须存在&#xff0c;不存在则抛出异常】w只写模式【不可读&#xff1b;不存在则创建&#xff1b;存在则清空内容】a之追加写模式【不可读&#xff1b;不…

python3 将unicode转中文

decrypted_str.encode(utf-8).decode(unicode_escape)

HTTP菜鸟教程速查手册

HTTP协议&#xff08;HyperText Transfer Protocol&#xff0c;超文本传输协议&#xff09;是因特网上应用最为广泛的一种网络传输协议&#xff0c;所有的WWW文件都必须遵守这个标准。 HTTP是一个基于TCP/IP通信协议来传递数据&#xff08;HTML 文件, 图片文件, 查询结果等&am…

mysql学习笔记01-创建数据库

创建数据库&#xff1a; 校验规则&#xff1a;是指表的排序规则和查询时候的规则 utf8_general_ci 支持中文&#xff0c; 且不区分大小写 utf8_bin 支持中文&#xff0c; 区分大小写 比如&#xff1a; create database db3 character set utf8 collate utf8_general_ci; &…

python的Web编程

首先看一下效果 完整代码 import socket from multiprocessing import ProcessHTML_ROOT_DIR ""def handle_client(client_socket):request_data client_socket.recv(1024)print("request data:", request_data)response_start_line "HTTP/1.0 20…

mysql 学习笔记 02创建表

表结构的创建 比如&#xff1a; create table userinfo (id int unsigned comment id号name varchar(60) comment 用户名password char(32),birthday date ) character set utf8 engine MyISAM;comment 表示注释的意思 不同的存储引擎&#xff0c;创建的表的文件不一样

mysql 学习笔记03 常用数据类型

数值类型&#xff1a; a. 整数类型&#xff1a; 注意事项&#xff1a; 举例&#xff1a;某个整型字段 &#xff0c;不为空&#xff0c;且有默认值 create table test (age int unisigned not null default 1);zerofill的使用 b. bit类型的使用 c.小数类型 小数类型占用…

VMware的虚拟机连不上网

1.如果你发现在VMware下运行的虚拟机无法连接网络&#xff0c;那下面的方法也许可以帮 到你。&#xff08;前提是你的物理网络是通的&#xff09; 第一步&#xff1a;在VMware界面下 单击“编辑“→”虚拟网络编辑器” 第二步&#xff1a;单击”更改设置” 获取权限&#xff…

python三国演义人物出场统计

完整代码 开源代码 统计三国演义人物高频次数 #!/usr/bin/env python # codingutf-8 #e10.4CalThreeKingdoms.py import jieba excludes {"来到","人马","领兵","将军","却说","荆州","二人","…

mysql 学习笔记03修改表以及其他操作

首先创建一张表 在现有表的结构上增加字段 alter table users add image varchar(100) not null defalut comment 图片路径;修改某个字段的长度 alter table users modify job vachar(60) not null comment 工作;删除某个字段 删除sex这个字段 alter table users drop se…

统计哈姆雷特文本中高频词的个数

统计哈姆雷特文本中高频词的个数 三国演义人物出场统计 开源代码 讲解视频 kouubuntu:~/python$ cat ClaHamlet.py #!/usr/bin/env python # codingutf-8#e10.1CalHamlet.py def getText():txt open("hamlet.txt", "r").read()txt txt.lower()for ch…

mysql 学习笔记04 insert与update语句

1.插入数据 注意事项&#xff1a; 字符和日期类型&#xff0c; 要用 单引号 括起来 insert into (), (), () 例如&#xff1a; insert into goods values(1, abc, 2.2), (2, def, 3.3);这种形式添加多条记录 insert 语句&#xff0c;如果没有指定字段名&#xff0c;则values …

PyCharm怎么关闭端口,解决端口占用问题

在进行web开发遇到这个问题&#xff01;

mysql 笔记05 select语句以及条件语句的使用

select语句 过滤重复语句&#xff08;distinct&#xff09; 举例&#xff1a; 查询学生的总分 select name, math English China as 总分 from students;在姓赵的学生总分基础上&#xff0c; 增加60%&#xff0c; select name, round((math English China) * 1.6, 2) as …

python3 与 Django 连接数据库:Error loading MySQLdb module: No module named 'MySQLdb'

解决方法&#xff1a;在 init.py 文件中添加以下代码即可。 import pymysql pymysql.install_as_MySQLdb()

mysql 学习笔记05 统计函数的相关使用

合计函数count&#xff0c; 统计多少条记录 统计共有多少学生 select count(*) from students;查询数学成绩大于等于90的学生数量 select count(*) from students where math > 90;查询总分超过235分的学生的数量 select count(*) from students where (English math Ch…

Unknown column '' in 'field list'

Unknown column ‘’ in ‘field list’ 解决办法 正确写法&#xff1a;cursor.execute("update book set name%s where id%d" % (name, int(id))) 错误写法&#xff1a;cursor.execute("update book set name%s where id%d" % (name, int(id)))你要获取字…

mysql学习笔记06分组语句的使用

group by 子句 对列进行分组 有两张表&#xff1a; 一张为部门表&#xff0c; 一张为员工表统计 每个部门的平均工资&#xff0c;与最高工资 select avg(salary), max(salary) from emp group by deptno;统计 每个部门的每个岗位的 平均工资与最低工资&#xff08;注意这里的…