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.pswp.cn/news/382500.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/382500.shtml
英文地址,請注明出處:http://en.pswp.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;注意這里的…